ServerRequestCookieProvider::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 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 ServerRequestCookieProvider implements ServerRequestProviderInterface
10
{
11
    /**
12
     * @var array
13
     */
14
    public const DEFAULT_OPTIONS = [
15
        'cookieName' => 'jwt_token'
16
    ];
17
18
    /**
19
     * @var ServerRequestInterface
20
     */
21
    private $request;
22
23
    /**
24
     * @var bool
25
     */
26
    private $loaded = false;
27
28
    /**
29
     * @var string|null
30
     */
31
    private $tokenString;
32
33
    /**
34
     * @var string
35
     */
36
    private $cookieName;
37
38
    /**
39
     * HttpAuthenticationBearer constructor.
40
     *
41
     * @throws \InvalidArgumentException
42
     *
43
     * @param ServerRequestInterface $request
44
     * @param string[]               $options see self::DEFAULT_OPTIONS
45
     */
46 10
    public function __construct(ServerRequestInterface $request, array $options = [])
47
    {
48 10
        $this->request = $request;
49 10
        $this->cookieName = trim($options['cookieName'] ?? self::DEFAULT_OPTIONS['cookieName']);
50 10
        if ($this->cookieName === '') {
51 1
            throw new \InvalidArgumentException('cookieName option parameter cannot be empty');
52
        }
53 9
    }
54
55
    /**
56
     * @return bool
57
     */
58 2
    public function hasToken(): bool
59
    {
60 2
        if (!$this->loaded) {
61 1
            $this->loadTokenFromCookie();
62
        }
63
64 2
        return $this->tokenString !== null;
65
    }
66
67
    /**
68
     * Return token string.
69
     *
70
     *
71
     * @return string|null
72
     */
73 7
    public function getPlainToken(): ?string
74
    {
75 7
        if (!$this->loaded) {
76 7
            $this->loadTokenFromCookie();
77
        }
78
79 7
        return $this->tokenString;
80
    }
81
82 8
    protected function loadTokenFromCookie(): void
83
    {
84 8
        $cookies = $this->request->getCookieParams();
85 8
        $this->tokenString = $cookies[$this->cookieName] ?? null;
86 8
        $this->loaded = true;
87 8
    }
88
}
89