Completed
Push — master ( 224127...d5dc6c )
by Alejandro
28s
created

RequestToHttpAuthPlugin::hasAnySupportedHeader()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 1
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
ccs 6
cts 6
cp 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Authentication;
5
6
use Psr\Container;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException;
9
use function array_filter;
10
use function array_reduce;
11
use function array_shift;
12
13
class RequestToHttpAuthPlugin implements RequestToHttpAuthPluginInterface
14
{
15
    // Headers here have to be defined in order of priority.
16
    // When more than one is matched, the first one to be found will take precedence.
17
    public const SUPPORTED_AUTH_HEADERS = [
18
        Plugin\ApiKeyHeaderPlugin::HEADER_NAME,
19
        Plugin\AuthorizationHeaderPlugin::HEADER_NAME,
20
    ];
21
22
    /**
23
     * @var AuthenticationPluginManagerInterface
24
     */
25
    private $authPluginManager;
26
27 4
    public function __construct(AuthenticationPluginManagerInterface $authPluginManager)
28
    {
29 4
        $this->authPluginManager = $authPluginManager;
30 4
    }
31
32
    /**
33
     * @throws Container\ContainerExceptionInterface
34
     * @throws NoAuthenticationException
35
     */
36 4
    public function fromRequest(ServerRequestInterface $request): Plugin\AuthenticationPluginInterface
37
    {
38 4
        if (! $this->hasAnySupportedHeader($request)) {
39 1
            throw NoAuthenticationException::fromExpectedTypes([
40 1
                Plugin\ApiKeyHeaderPlugin::HEADER_NAME,
41
                Plugin\AuthorizationHeaderPlugin::HEADER_NAME,
42
            ]);
43
        }
44
45 3
        return $this->authPluginManager->get($this->getFirstAvailableHeader($request));
46
    }
47
48 4
    private function hasAnySupportedHeader(ServerRequestInterface $request): bool
49
    {
50 4
        return array_reduce(
51 4
            self::SUPPORTED_AUTH_HEADERS,
52
            function (bool $carry, string $header) use ($request) {
53 4
                return $carry || $request->hasHeader($header);
54 4
            },
55 4
            false
56
        );
57
    }
58
59 3
    private function getFirstAvailableHeader(ServerRequestInterface $request): string
60
    {
61 3
        $foundHeaders = array_filter(self::SUPPORTED_AUTH_HEADERS, [$request, 'hasHeader']);
62 3
        return array_shift($foundHeaders) ?? '';
63
    }
64
}
65