Passed
Pull Request — master (#18)
by Alexander
03:04
created

Composite::authenticate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 2
b 0
f 0
nc 4
nop 1
dl 0
loc 14
ccs 7
cts 8
cp 0.875
crap 4.0312
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Auth\Method;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Yiisoft\Auth\AuthenticationMethodInterface;
10
use Yiisoft\Auth\IdentityInterface;
11
12
/**
13
 * Composite allows multiple authentication methods at the same time.
14
 */
15
final class Composite implements AuthenticationMethodInterface
16
{
17
    /**
18
     * @var AuthenticationMethodInterface[]
19
     */
20
    private array $authenticationMethods;
21
22
    /**
23
     * @param AuthenticationMethodInterface[] $methods
24
     */
25 4
    public function __construct(array $methods)
26
    {
27 4
        $this->authenticationMethods = $methods;
28 4
    }
29
30 3
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
31
    {
32 3
        foreach ($this->authenticationMethods as $authenticationMethod) {
33 2
            if (!$authenticationMethod instanceof AuthenticationMethodInterface) {
34
                throw new \RuntimeException('Authentication method must be an instance of ' . AuthenticationMethodInterface::class . '.');
35
            }
36
37 2
            $identity = $authenticationMethod->authenticate($request);
38 2
            if ($identity !== null) {
39 2
                return $identity;
40
            }
41
        }
42
43 2
        return null;
44
    }
45
46 1
    public function challenge(ResponseInterface $response): ResponseInterface
47
    {
48 1
        foreach ($this->authenticationMethods as $method) {
49 1
            $response = $method->challenge($response);
50
        }
51 1
        return $response;
52
    }
53
}
54