Cookie::clear()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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