AuthLdap::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace kalanis\kw_auth_sources\Sources\Mapper;
4
5
6
use kalanis\kw_accounts\AccountsException;
7
use kalanis\kw_accounts\Interfaces\IAuth;
8
use kalanis\kw_accounts\Interfaces\IUser;
9
use kalanis\kw_mapper\MapperException;
10
11
12
/**
13
 * Class AuthLdap
14
 * @package kalanis\kw_auth_sources\Sources\Mapper
15
 * Authenticate via ldap
16
 * need kw_mapper!
17
 * @codeCoverageIgnore because access external content
18
 */
19
class AuthLdap implements IAuth
20
{
21
    protected Ldap\LdapRecord $record;
22
23 1
    public function __construct()
24
    {
25 1
        $this->record = new Ldap\LdapRecord();
26 1
    }
27
28
    public function authenticate(string $userName, array $params = []): ?IUser
29
    {
30
        try {
31
            $mapper = $this->record->getMapper();
32
            if (!method_exists($mapper, 'authorize')) {
33
                return null;
34
            }
35
            /** @var Ldap\LdapMapper $mapper */
36
            return ($mapper->authorize([
37
                'user' => strval($userName),
38
                'password' => strval($params['password'] ?: '')
39
            ]))
40
                ? $this->getDataOnly($userName)
41
                : null ;
42
        } catch (MapperException $ex) {
43
            throw new AccountsException($ex->getMessage(), $ex->getCode(), $ex);
44
        }
45
    }
46
47
    public function getDataOnly(string $userName): ?IUser
48
    {
49
        try {
50
            $record = clone $this->record;
51
            $record->name = $userName;
52
            $record->load();
53
            return (empty($record->getAuthId())) ? null : $record ;
54
        } catch (MapperException $ex) {
55
            throw new AccountsException($ex->getMessage(), $ex->getCode(), $ex);
56
        }
57
    }
58
}
59