LdapHelpers   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 62
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A escapeFilterValue() 0 28 4
A asc2hex32() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\ldap\Connector;
6
7
use SimpleSAML\Utils;
8
9
use function dechex;
10
use function ord;
11
use function str_pad;
12
use function str_replace;
13
use function strlen;
14
use function substr;
15
16
trait LdapHelpers
17
{
18
    /**
19
     * Escapes the given VALUES according to RFC 2254 so that they can be safely used in LDAP filters.
20
     *
21
     * Any control characters with an ASCII code < 32 as well as the characters with special meaning in
22
     * LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a
23
     * backslash followed by two hex digits representing the hexadecimal value of the character.
24
     *
25
     * @param string|string[] $values Array of values to escape
26
     * @param bool $singleValue
27
     * @return string|string[] Array $values, but escaped
28
     */
29
    public function escapeFilterValue(string|array $values = [], bool $singleValue = true)
30
    {
31
        // Parameter validation
32
        $arrayUtils = new Utils\Arrays();
33
        $values = $arrayUtils->arrayize($values);
34
35
        foreach ($values as $key => $val) {
36
            if ($val === null) {
37
                $val = '\0'; // apply escaped "null" if string is empty
38
            } else {
39
                // Escaping of filter meta characters
40
                $val = str_replace('\\', '\5c', $val);
41
                $val = str_replace('*', '\2a', $val);
42
                $val = str_replace('(', '\28', $val);
43
                $val = str_replace(')', '\29', $val);
44
45
                // ASCII < 32 escaping
46
                $val = $this->asc2hex32($val);
47
            }
48
49
            $values[$key] = $val;
50
        }
51
52
        if ($singleValue) {
53
            return $values[0];
54
        }
55
56
        return $values;
57
    }
58
59
60
    /**
61
     * Converts all ASCII chars < 32 to "\HEX"
62
     *
63
     * @param string $string String to convert
64
     * @return string
65
     */
66
    public function asc2hex32(string $string): string
67
    {
68
        for ($i = 0; $i < strlen($string); $i++) {
69
            $char = substr($string, $i, 1);
70
71
            if (ord($char) < 32) {
72
                $hex = str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
73
                $string = str_replace($char, '\\' . $hex, $string);
74
            }
75
        }
76
77
        return $string;
78
    }
79
}
80