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

ServerRequestCookieProvider::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
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 array                  $options see self::DEFAULT_OPTIONS
45
     */
46
    public function __construct(ServerRequestInterface $request, array $options = [])
47
    {
48
        $this->request = $request;
49
        $this->cookieName = trim((string) ($options['cookieName'] ?? self::DEFAULT_OPTIONS['cookieName']));
50
        if ($this->cookieName === '') {
51
            throw new \InvalidArgumentException('cookieName option parameter cannot be empty');
52
        }
53
    }
54
55
    /**
56
     * @return bool
57
     */
58
    public function hasToken(): bool
59
    {
60
        if (!$this->loaded) {
61
            $this->loadTokenFromCookie();
62
        }
63
64
        return $this->tokenString !== null;
65
    }
66
67
    /**
68
     * Return token string.
69
     *
70
     *
71
     * @return string|null
72
     */
73
    public function getPlainToken(): ?string
74
    {
75
        if (!$this->loaded) {
76
            $this->loadTokenFromCookie();
77
        }
78
79
        return $this->tokenString;
80
    }
81
82
    protected function loadTokenFromCookie(): void
83
    {
84
        $cookies = $this->request->getCookieParams();
85
        $this->tokenString = $cookies[$this->cookieName] ?? null;
86
        $this->loaded = true;
87
    }
88
}
89