Passed
Push — master ( c0d33c...41aaf7 )
by Arnold
15:34 queued 05:37
created

Cookie   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 14
dl 0
loc 56
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 3 1
A set() 0 9 2
A clear() 0 9 2
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\Auth\Session\Jwt;
6
7
/**
8
 * Use global `$_COOKIE` and `setcookie()` for the JWT cookie.
9
 *
10
 * @codeCoverageIgnore
11
 */
12
class Cookie implements CookieInterface
13
{
14
    protected string $name;
15
16
    /**
17
     * Options for `setcookie()`
18
     * @var array<string,mixed>
19
     */
20
    protected array $options;
21
22
    /**
23
     * Cookies constructor.
24
     *
25
     * @param string              $name
26
     * @param array<string,mixed> $options
27
     */
28
    public function __construct(string $name, array $options = [])
29
    {
30
        $this->name = $name;
31
        $this->options = array_change_key_case($options, CASE_LOWER);
32
    }
33
34
    /**
35
     * @inheritDoc
36
     */
37
    public function get(): ?string
38
    {
39
        return $_COOKIE[$this->name] ?? null;
40
    }
41
42
    /**
43
     * @inheritDoc
44
     */
45
    public function set(string $value, int $expire): void
46
    {
47
        $success = setcookie($this->name, $value, ['expire' => $expire] + $this->options);
48
49
        if (!$success) {
50
            throw new \RuntimeException("Failed to set cookie '{$this->name}'");
51
        }
52
53
        $_COOKIE[$this->name] = $value;
54
    }
55
56
    /**
57
     * @inheritDoc
58
     */
59
    public function clear(): void
60
    {
61
        $success = setcookie($this->name, '', ['expire' => 1] +  $this->options);
62
63
        if (!$success) {
64
            throw new \RuntimeException("Failed to clear cookie '{$this->name}'");
65
        }
66
67
        unset($_COOKIE[$this->name]);
68
    }
69
}
70