Completed
Push — master ( 52244a...079467 )
by Sébastien
07:24
created

loadTokenFromRequest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Soluble\Wallit\Token\Provider;
6
7
use Psr\Http\Message\ServerRequestInterface;
8
9
class ServerRequestAuthBearerProvider implements ServerRequestProviderInterface
10
{
11
    /**
12
     * @var array
13
     */
14
    public const DEFAULT_OPTIONS = [
15
        'httpHeader' => 'Authentication',
16
        'httpHeaderPrefix' => 'Bearer '
17
    ];
18
19
    /**
20
     * @var ServerRequestInterface
21
     */
22
    private $request;
23
24
    /**
25
     * @var bool
26
     */
27
    private $loaded = false;
28
29
    /**
30
     * @var string|null
31
     */
32
    private $tokenString;
33
34
    /**
35
     * @var string
36
     */
37
    private $httpHeader;
38
39
    /**
40
     * @var string
41
     */
42
    private $httpHeaderPrefix;
43
44
    /**
45
     * HttpAuthenticationBearer constructor.
46
     *
47
     * @throws \InvalidArgumentException
48
     *
49
     * @param ServerRequestInterface $request
50
     * @param array                  $options
51
     */
52
    public function __construct(ServerRequestInterface $request, array $options = [])
53
    {
54
        $this->request = $request;
55
56
        $this->httpHeader = trim((string) ($options['httpHeader'] ?? self::DEFAULT_OPTIONS['httpHeader']));
57
        $this->httpHeaderPrefix = (string) ($options['httpHeaderPrefix'] ?? self::DEFAULT_OPTIONS['httpHeaderPrefix']);
58
59
        if ($this->httpHeader === '') {
60
            throw new \InvalidArgumentException('httpHeader option cannot be empty.');
61
        }
62
    }
63
64
    /**
65
     * @return bool
66
     */
67
    public function hasToken(): bool
68
    {
69
        if (!$this->loaded) {
70
            $this->loadTokenFromRequest();
71
        }
72
73
        return $this->tokenString !== null;
74
    }
75
76
    /**
77
     * Return token string.
78
     *
79
     * @return string|null
80
     */
81
    public function getPlainToken(): ?string
82
    {
83
        if (!$this->loaded) {
84
            $this->loadTokenFromRequest();
85
        }
86
87
        return $this->tokenString;
88
    }
89
90
    protected function loadTokenFromRequest(): void
91
    {
92
        $headers = $this->request->getHeader($this->httpHeader);
93
        foreach ($headers as $header) {
94
            if ($this->httpHeaderPrefix !== '') {
95
                if (strpos($header, $this->httpHeaderPrefix) === 0) {
96
                    $this->tokenString = trim(str_replace($this->httpHeaderPrefix, '', $header));
97
                }
98
            } else {
99
                $this->tokenString = trim($header);
100
            }
101
        }
102
        $this->loaded = true;
103
    }
104
}
105