Passed
Push — master ( 999269...d48b48 )
by Alexander
01:20
created

Composite::setAuthMethods()   A

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