Completed
Push — master ( 99c4e8...3c79d6 )
by Alexander
02:19
created

CompositeAuth   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 46
ccs 0
cts 30
cp 0
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A challenge() 0 6 2
A setAuthMethods() 0 3 1
A __construct() 0 3 1
A authenticate() 0 17 5
1
<?php
2
namespace Yiisoft\Yii\Web\Auth;
3
4
use Psr\Container\ContainerInterface;
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Yiisoft\Yii\Web\User\IdentityInterface;
8
9
/**
10
 * CompositeAuth allows multiple authentication methods at the same time.
11
 *
12
 * The authentication methods contained by CompositeAuth are configured via {@see setAuthMethods()},
13
 * which is a list of supported authentication class configurations.
14
 */
15
final class CompositeAuth implements AuthInterface
16
{
17
    /**
18
     * @var AuthInterface[]
19
     */
20
    private $authMethods = [];
21
    /**
22
     * @var ContainerInterface
23
     */
24
    private $container;
25
26
    public function __construct(ContainerInterface $container)
27
    {
28
        $this->container = $container;
29
    }
30
31
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
32
    {
33
        foreach ($this->authMethods as $i => $auth) {
34
            if (!$auth instanceof AuthInterface) {
35
                $this->authMethods[$i] = $auth = $this->container->get($auth);
36
                if (!$auth instanceof AuthInterface) {
37
                    throw new \RuntimeException(get_class($auth) . ' must implement ' . AuthInterface::class);
38
                }
39
            }
40
41
            $identity = $auth->authenticate($request);
42
            if ($identity !== null) {
43
                return $identity;
44
            }
45
        }
46
47
        return null;
48
    }
49
50
    public function challenge(ResponseInterface $response): ResponseInterface
51
    {
52
        foreach ($this->authMethods as $method) {
53
            $response = $method->challenge($response);
54
        }
55
        return $response;
56
    }
57
58
    public function setAuthMethods(array $methods): void
59
    {
60
        $this->authMethods = $methods;
61
    }
62
}
63