Cookies::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\SSO\Broker;
6
7
/**
8
 * Use global $_COOKIE and setcookie() to persist the client token.
9
 *
10
 * @implements \ArrayAccess<string,mixed>
11
 * @codeCoverageIgnore
12
 */
13
class Cookies implements \ArrayAccess
14
{
15
    /** @var int */
16
    protected int $ttl;
17
18
    /** @var string */
19
    protected string $path;
20
21
    /** @var string */
22
    protected string $domain;
23
24
    /** @var bool */
25
    protected bool $secure;
26
27
    public function __construct(int $ttl = 3600, string $path = '', string $domain = '', bool $secure = false)
28
    {
29
        $this->ttl = $ttl;
30
        $this->path = $path;
31
        $this->domain = $domain;
32
        $this->secure = $secure;
33
    }
34
35
    /**
36
     * @inheritDoc
37
     */
38
    public function offsetExists(mixed $offset): bool
39
    {
40
        return isset($_COOKIE[$offset]);
41
    }
42
43
    /**
44
     * @inheritDoc
45
     */
46
    public function offsetGet(mixed $offset): mixed
47
    {
48
        return $_COOKIE[$offset] ?? null;
49
    }
50
51
    /**
52
     * @inheritDoc
53
     */
54
    public function offsetSet(mixed $offset, mixed $value): void
55
    {
56
        $success = setcookie($offset, $value, time() + $this->ttl, $this->path, $this->domain, $this->secure, true);
57
58
        if (!$success) {
59
            throw new \RuntimeException("Failed to set cookie '$offset'");
60
        }
61
62
        $_COOKIE[$offset] = $value;
63
    }
64
65
    /**
66
     * @inheritDoc
67
     */
68
    public function offsetUnset(mixed $offset): void
69
    {
70
        setcookie($offset, '', 1, $this->path, $this->domain, $this->secure, true);
71
        unset($_COOKIE[$offset]);
72
    }
73
}
74