1<?php
2
3/**
4 * This file is part of the FreeDSx LDAP package.
5 *
6 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace FreeDSx\Ldap\Entry;
13
14use function bin2hex;
15use function implode;
16use function preg_match;
17use function preg_replace_callback;
18use function str_split;
19
20/**
21 * Some common methods around escaping attribute values and RDN values.
22 *
23 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
24 */
25trait EscapeTrait
26{
27    /**
28     * Escape all characters in a value.
29     *
30     * @param string $value
31     * @return string
32     */
33    public static function escapeAll(string $value): string
34    {
35        if (self::shouldNotEscape($value)) {
36            return $value;
37        }
38
39        return '\\' . implode('\\', str_split(bin2hex($value), 2));
40    }
41
42    /**
43     * Replace non-printable ASCII with escaped hex.
44     */
45    protected static function escapeNonPrintable(string $value): string
46    {
47        return (string) preg_replace_callback('/([\x00-\x1F\x7F])/', function ($matches) {
48            return '\\' . bin2hex($matches[1]);
49        }, $value);
50    }
51
52    protected static function shouldNotEscape(string $value): bool
53    {
54        return (preg_match('/^(\\\\[0-9A-Fa-f]{2})+$/', $value) === 1 || $value === '');
55    }
56}
57