Completed
Push — master ( 78a8ff...f55562 )
by Christopher
02:55
created

LdapUtils::implodeDn()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
/**
3
 * This file is part of the LdapTools package.
4
 *
5
 * (c) Chad Sikorra <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace chrmorandi\ldap;
12
13
14
/**
15
 * Some common helper LDAP functions.
16
 *
17
 * @author Chad Sikorra <[email protected]>
18
 */
19
class LdapUtils
20
{
21
    
22
    /**
23
     * Converts a string distinguished name into its separate pieces.
24
     *
25
     * @param string $dn
26
     * @param int $withAttributes Set to 0 to get the attribute names along with the value.
27
     * @return array
28
     */
29
    public static function explodeDn($dn, $withAttributes = 1)
30
    {
31
        $pieces = ldap_explode_dn($dn, $withAttributes);
32
33
        if ($pieces === false || !isset($pieces['count']) || $pieces['count'] == 0) {
34
            throw new \yii\base\InvalidParamException(sprintf('Unable to parse DN "%s".', $dn));
35
        }
36
        unset($pieces['count']);
37
        return $pieces;
38
    }
39
40
    /**
41
     * Given a DN as an array in ['cn=Name', 'ou=Employees', 'dc=example', 'dc=com'] form, return it as its string
42
     * representation that is safe to pass back to a query or to save back to LDAP for a DN.
43
     *
44
     * @param array $dn
45
     * @return string
46
     */
47
    public static function implodeDn(array $dn)
48
    {
49
        foreach ($dn as $index => $piece) {
50
            $values = explode('=', $piece, 2);
51
            if (count($values) === 1) {
52
                throw new InvalidArgumentException(sprintf('Unable to parse DN piece "%s".', $values[0]));
53
            }
54
            $dn[$index] = $values[0].'='.$values[1];
55
        }
56
57
        return implode(',', $dn);
58
    }
59
60
    /**
61
     * Given a full escaped DN return the RDN in escaped form.
62
     *
63
     * @param string $dn
64
     * @return string
65
     */
66
    public static function getRdnFromDn($dn)
67
    {
68
        $rdn = self::explodeDn($dn, 0)[0];
69
        $rdn = explode('=', $rdn, 2);
70
71
        return $rdn[0].'='.$rdn[1];
72
    }
73
74
}
75