Cookies::has()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dflydev\FigCookies;
6
7
use Psr\Http\Message\RequestInterface;
8
use function array_values;
9
use function implode;
10
11
class Cookies
12
{
13
    /**
14
     * The name of the Cookie header.
15
     */
16
    public const COOKIE_HEADER = 'Cookie';
17
18
    /** @var Cookie[] */
19
    private $cookies = [];
20
21
    /** @param Cookie[] $cookies */
22 23
    public function __construct(array $cookies = [])
23
    {
24 23
        foreach ($cookies as $cookie) {
25 18
            $this->cookies[$cookie->getName()] = $cookie;
26 23
        }
27 23
    }
28
29
    public function has(string $name) : bool
30
    {
31
        return isset($this->cookies[$name]);
32
    }
33 15
34
    public function get(string $name) : ?Cookie
35 15
    {
36
        if (! $this->has($name)) {
37
            return null;
38
        }
39
40
        return $this->cookies[$name];
41
    }
42 10
43
    /** @return Cookie[] */
44 10
    public function getAll() : array
45
    {
46
        return array_values($this->cookies);
47
    }
48 10
49
    public function with(Cookie $cookie) : Cookies
50
    {
51
        $clone = clone($this);
52
53
        $clone->cookies[$cookie->getName()] = $cookie;
54 6
55
        return $clone;
56 6
    }
57
58
    public function without(string $name) : Cookies
59
    {
60
        $clone = clone($this);
61
62
        if (! $clone->has($name)) {
63 7
            return $clone;
64
        }
65 7
66
        unset($clone->cookies[$name]);
67 7
68
        return $clone;
69 7
    }
70
71
    /**
72
     * Render Cookies into a Request.
73
     */
74
    public function renderIntoCookieHeader(RequestInterface $request) : RequestInterface
75
    {
76 3
        $cookieString = implode('; ', $this->cookies);
77
78 3
        $request = $request->withHeader(static::COOKIE_HEADER, $cookieString);
79
80 3
        return $request;
81
    }
82
83
    /**
84 3
     * Create Cookies from a Cookie header value string.
85
     *
86 3
     * @return static
87
     */
88
    public static function fromCookieString(string $string) : self
89
    {
90
        return new static(Cookie::listFromCookieString($string));
91
    }
92
93
    public static function fromRequest(RequestInterface $request) : Cookies
94
    {
95 7
        $cookieString = $request->getHeaderLine(static::COOKIE_HEADER);
96
97 7
        return static::fromCookieString($cookieString);
98
    }
99
}
100