Cookie::listFromCookieString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dflydev\FigCookies;
6
7
use function array_map;
8
use function urlencode;
9
10
class Cookie
11
{
12
    /** @var string */
13
    private $name;
14
15
    /** @var string|null */
16
    private $value;
17
18
    public function __construct(string $name, ?string $value = null)
19
    {
20
        $this->name  = $name;
21 25
        $this->value = $value;
22
    }
23 25
24 25
    public function getName() : string
25 25
    {
26
        return $this->name;
27
    }
28
29
    public function getValue() : ?string
30 25
    {
31
        return $this->value;
32 25
    }
33
34
    public function withValue(?string $value = null) : Cookie
35
    {
36
        $clone = clone($this);
37
38 10
        $clone->value = $value;
39
40 10
        return $clone;
41
    }
42
43
    /**
44
     * Render Cookie as a string.
45
     *
46
     */
47 23
    public function __toString() : string
48
    {
49 23
        return urlencode($this->name) . '=' . urlencode((string) $this->value);
50
    }
51 23
52
    /**
53 23
     * Create a Cookie.
54
     *
55
     */
56
    public static function create(string $name, ?string $value = null) : Cookie
57
    {
58
        return new static($name, $value);
59
    }
60
61 7
    /**
62
     * Create a list of Cookies from a Cookie header value string.
63 7
     *
64
     * @return Cookie[]
65
     */
66
    public static function listFromCookieString(string $string) : array
67
    {
68
        $cookies = StringUtil::splitOnAttributeDelimiter($string);
69
70
        return array_map(function ($cookiePair) {
71
            return static::oneFromCookiePair($cookiePair);
72
        }, $cookies);
73 4
    }
74
75 4
    /**
76
     * Create one Cookie from a cookie key/value header value string.
77
     *
78
     */
79
    public static function oneFromCookiePair(string $string) : Cookie
80
    {
81
        list ($cookieName, $cookieValue) = StringUtil::splitCookiePair($string);
82
83
        /** @var Cookie $cookie */
84 23
        $cookie = new static($cookieName);
85
86 23
        if ($cookieValue !== null) {
87
            $cookie = $cookie->withValue($cookieValue);
88 23
        }
89 20
90 23
        return $cookie;
91
    }
92
}
93