Passed
Pull Request — master (#37)
by Tim
28:28 queued 20:25
created

ConnectorFactory::fromAuthSource()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 17
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\ldap;
6
7
use SimpleSAML\Assert\Assert;
8
use SimpleSAML\Configuration;
9
use SimpleSAML\Error;
10
use SimpleSAML\Module;
11
use SimpleSAML\Module\ldap\Connector;
12
use SimpleSAML\Module\ldap\Auth\Source\Ldap;
13
14
use function current;
15
use function sprintf;
16
17
class ConnectorFactory
18
{
19
    /**
20
     * @param string $authSource
21
     * @return \SimpleSAML\Module\ldap\ConnectorInterface
22
     */
23
    public static function fromAuthSource(string $authSource): ConnectorInterface
24
    {
25
        // Get the authsources file, which should contain the config
26
        $authSources = Configuration::getConfig('authsources.php');
27
28
        // Verify that the authsource config exists
29
        if (!$authSources->hasValue($authSource)) {
30
            throw new Error\Exception(sprintf(
31
                'Authsource [%s] not found in authsources.php',
32
                $authSource
33
            ));
34
        }
35
36
        // Get just the specified authsource config values
37
        $ldapConfig = $authSources->getArray($authSource);
38
39
        return self::fromAuthSourceConfig($ldapConfig);
40
    }
41
42
43
    /**
44
     * @param array $authSourceConfig
45
     * @return \SimpleSAML\Module\ldap\ConnectorInterface
46
     */
47
    public static function fromAuthSourceConfig(array $ldapConfig): ConnectorInterface
48
    {
49
        $ldapConfig = Configuration::loadFromArray($ldapConfig);
50
51
        $encryption = $ldapConfig->getOptionalString('encryption', 'ssl');
52
        Assert::oneOf($encryption, ['none', 'ssl', 'tls']);
53
54
        $version = $ldapConfig->getOptionalInteger('version', 3);
55
        Assert::positiveInteger($version);
56
57
        $class = $ldapConfig->getOptionalString('connector', Connector\Ldap::class);
58
        Assert::classExists($class);
59
        Assert::implementsInterface($class, ConnectorInterface::class);
60
61
        return /** @psalm-var \SimpleSAML\Module\ldap\ConnectionInterface */ new $class(
62
            $ldapConfig->getString('connection_string'),
63
            $encryption,
64
            $version,
65
            $ldapConfig->getOptionalString('extension', 'ext_ldap'),
66
            $ldapConfig->getOptionalBoolean('debug', false),
67
            [
68
                'network_timeout' => $ldapConfig->getOptionalInteger('timeout', 3),
69
                'referrals' => $ldapConfig->getOptionalBoolean('referrals', false),
70
            ]
71
        );
72
    }
73
}
74