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;
13
14use function array_keys;
15use function array_values;
16use function str_ireplace;
17use function str_replace;
18
19/**
20 * Some common methods for LDAP URLs and URL Extensions.
21 *
22 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
23 */
24trait LdapUrlTrait
25{
26    /**
27     * @var array
28     */
29    protected static $escapeMap = [
30        '%' => '%25',
31        '?' => '%3f',
32        ' ' => '%20',
33        '<' => '%3c',
34        '>' => '%3e',
35        '"' => '%22',
36        '#' => '%23',
37        '{' => '%7b',
38        '}' => '%7d',
39        '|' => '%7c',
40        '\\' => '%5c',
41        '^' => '%5e',
42        '~' => '%7e',
43        '[' => '%5b',
44        ']' => '%5d',
45        '`' => '%60',
46    ];
47
48    /**
49     * Percent-encode certain values in the URL.
50     *
51     * @param null|string $value
52     * @return string
53     */
54    protected static function encode(?string $value): string
55    {
56        return str_replace(
57            array_keys(self::$escapeMap),
58            array_values(self::$escapeMap),
59            (string) $value
60        );
61    }
62
63    /**
64     * Percent-decode values from the URL.
65     *
66     * @param string $value
67     * @return string
68     */
69    protected static function decode(string $value): string
70    {
71        return str_ireplace(
72            array_values(self::$escapeMap),
73            array_keys(self::$escapeMap),
74            $value
75        );
76    }
77}
78