Passed
Push — master ( c858e1...becd64 )
by Filipe
12:31 queued 19s
created

HeaderAccessTokenExtractor   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 11
dl 0
loc 31
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A extractAccessToken() 0 13 4
1
<?php
2
3
/**
4
 * This file is part of web-stack
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Slick\WebStack\Domain\Security\Http\AccessToken\Extractor;
13
14
use Psr\Http\Message\ServerRequestInterface;
15
use Slick\WebStack\Domain\Security\Http\AccessToken\AccessTokenExtractorInterface;
16
17
/**
18
 * HeaderAccessTokenExtractor
19
 *
20
 * @package Slick\WebStack\Domain\Security\Http\AccessToken\Extractor
21
 */
22
final class HeaderAccessTokenExtractor implements AccessTokenExtractorInterface
23
{
24
25
    private string $regex;
26
27
    public function __construct(
28
        private readonly string $headerParameter = 'Authorization',
29
        private readonly string $tokenType = 'Bearer',
30
    ) {
31
        $this->regex = sprintf(
32
            '/^%s([a-zA-Z0-9\-_\+~\/\.]+=*)$/',
33
            '' === $this->tokenType ? '' : preg_quote($this->tokenType).'\s+'
34
        );
35
    }
36
37
    /**
38
     * @inheritDoc
39
     */
40
    public function extractAccessToken(ServerRequestInterface $request): ?string
41
    {
42
        if (!$request->hasHeader($this->headerParameter) ||
43
            !is_string($header = $request->getHeaderLine($this->headerParameter))
44
        ) {
45
            return null;
46
        }
47
48
        if (preg_match($this->regex, $header, $matches)) {
49
            return $matches[1];
50
        }
51
52
        return null;
53
    }
54
}
55