Completed
Push — security-enhancements ( 371440 )
by Alexander
08:04
created

CookieCollection::fromArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2
Metric Value
dl 0
loc 4
rs 10
ccs 0
cts 3
cp 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use ArrayIterator;
12
use yii\base\InvalidCallException;
13
use yii\base\Object;
14
15
/**
16
 * CookieCollection maintains the cookies available in the current request.
17
 *
18
 * @property integer $count The number of cookies in the collection. This property is read-only.
19
 * @property ArrayIterator $iterator An iterator for traversing the cookies in the collection. This property
20
 * is read-only.
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @since 2.0
24
 */
25
class CookieCollection extends Object implements \IteratorAggregate, \ArrayAccess, \Countable
26
{
27
    /**
28
     * @var boolean whether this collection is read only.
29
     */
30
    public $readOnly = false;
31
32
    /**
33
     * @var Cookie[] the cookies in this collection (indexed by the cookie names)
34
     */
35
    private $_cookies = [];
36
37
38
    /**
39
     * Constructor.
40
     * @param array $cookies the cookies that this collection initially contains. This should be
41
     * an array of name-value pairs.
42
     * @param array $config name-value pairs that will be used to initialize the object properties
43
     */
44 19
    public function __construct($cookies = [], $config = [])
45
    {
46 19
        $this->_cookies = $cookies;
47 19
        parent::__construct($config);
48 19
    }
49
50
    /**
51
     * Returns an iterator for traversing the cookies in the collection.
52
     * This method is required by the SPL interface [[\IteratorAggregate]].
53
     * It will be implicitly called when you use `foreach` to traverse the collection.
54
     * @return ArrayIterator an iterator for traversing the cookies in the collection.
55
     */
56
    public function getIterator()
57
    {
58
        return new ArrayIterator($this->_cookies);
59
    }
60
61
    /**
62
     * Returns the number of cookies in the collection.
63
     * This method is required by the SPL `Countable` interface.
64
     * It will be implicitly called when you use `count($collection)`.
65
     * @return integer the number of cookies in the collection.
66
     */
67
    public function count()
68
    {
69
        return $this->getCount();
70
    }
71
72
    /**
73
     * Returns the number of cookies in the collection.
74
     * @return integer the number of cookies in the collection.
75
     */
76
    public function getCount()
77
    {
78
        return count($this->_cookies);
79
    }
80
81
    /**
82
     * Returns the cookie with the specified name.
83
     * @param string $name the cookie name
84
     * @return Cookie the cookie with the specified name. Null if the named cookie does not exist.
85
     * @see getValue()
86
     */
87
    public function get($name)
88
    {
89
        return isset($this->_cookies[$name]) ? $this->_cookies[$name] : null;
90
    }
91
92
    /**
93
     * Returns the value of the named cookie.
94
     * @param string $name the cookie name
95
     * @param mixed $defaultValue the value that should be returned when the named cookie does not exist.
96
     * @return mixed the value of the named cookie.
97
     * @see get()
98
     */
99 19
    public function getValue($name, $defaultValue = null)
100
    {
101 19
        return isset($this->_cookies[$name]) ? $this->_cookies[$name]->value : $defaultValue;
102
    }
103
104
    /**
105
     * Returns whether there is a cookie with the specified name.
106
     * Note that if a cookie is marked for deletion from browser, this method will return false.
107
     * @param string $name the cookie name
108
     * @return boolean whether the named cookie exists
109
     * @see remove()
110
     */
111
    public function has($name)
112
    {
113
        return isset($this->_cookies[$name]) && $this->_cookies[$name]->value !== ''
114
            && ($this->_cookies[$name]->expire === null || $this->_cookies[$name]->expire >= time());
115
    }
116
117
    /**
118
     * Adds a cookie to the collection.
119
     * If there is already a cookie with the same name in the collection, it will be removed first.
120
     * @param Cookie $cookie the cookie to be added
121
     * @throws InvalidCallException if the cookie collection is read only
122
     */
123
    public function add($cookie)
124
    {
125
        if ($this->readOnly) {
126
            throw new InvalidCallException('The cookie collection is read only.');
127
        }
128
        $this->_cookies[$cookie->name] = $cookie;
129
    }
130
131
    /**
132
     * Removes a cookie.
133
     * If `$removeFromBrowser` is true, the cookie will be removed from the browser.
134
     * In this case, a cookie with outdated expiry will be added to the collection.
135
     * @param Cookie|string $cookie the cookie object or the name of the cookie to be removed.
136
     * @param boolean $removeFromBrowser whether to remove the cookie from browser
137
     * @throws InvalidCallException if the cookie collection is read only
138
     */
139
    public function remove($cookie, $removeFromBrowser = true)
140
    {
141
        if ($this->readOnly) {
142
            throw new InvalidCallException('The cookie collection is read only.');
143
        }
144
        if ($cookie instanceof Cookie) {
145
            $cookie->expire = 1;
146
            $cookie->value = '';
147
        } else {
148
            $cookie = new Cookie([
149
                'name' => $cookie,
150
                'expire' => 1,
151
            ]);
152
        }
153
        if ($removeFromBrowser) {
154
            $this->_cookies[$cookie->name] = $cookie;
155
        } else {
156
            unset($this->_cookies[$cookie->name]);
157
        }
158
    }
159
160
    /**
161
     * Removes all cookies.
162
     * @throws InvalidCallException if the cookie collection is read only
163
     */
164
    public function removeAll()
165
    {
166
        if ($this->readOnly) {
167
            throw new InvalidCallException('The cookie collection is read only.');
168
        }
169
        $this->_cookies = [];
170
    }
171
172
    /**
173
     * Returns the collection as a PHP array.
174
     * @return array the array representation of the collection.
175
     * The array keys are cookie names, and the array values are the corresponding cookie objects.
176
     */
177
    public function toArray()
178
    {
179
        return $this->_cookies;
180
    }
181
182
    /**
183
     * Populates the cookie collection from an array.
184
     * @param array $array the cookies to populate from
185
     * @since 2.0.3
186
     */
187
    public function fromArray(array $array)
188
    {
189
        $this->_cookies = $array;
190
    }
191
192
    /**
193
     * Returns whether there is a cookie with the specified name.
194
     * This method is required by the SPL interface [[\ArrayAccess]].
195
     * It is implicitly called when you use something like `isset($collection[$name])`.
196
     * @param string $name the cookie name
197
     * @return boolean whether the named cookie exists
198
     */
199
    public function offsetExists($name)
200
    {
201
        return $this->has($name);
202
    }
203
204
    /**
205
     * Returns the cookie with the specified name.
206
     * This method is required by the SPL interface [[\ArrayAccess]].
207
     * It is implicitly called when you use something like `$cookie = $collection[$name];`.
208
     * This is equivalent to [[get()]].
209
     * @param string $name the cookie name
210
     * @return Cookie the cookie with the specified name, null if the named cookie does not exist.
211
     */
212
    public function offsetGet($name)
213
    {
214
        return $this->get($name);
215
    }
216
217
    /**
218
     * Adds the cookie to the collection.
219
     * This method is required by the SPL interface [[\ArrayAccess]].
220
     * It is implicitly called when you use something like `$collection[$name] = $cookie;`.
221
     * This is equivalent to [[add()]].
222
     * @param string $name the cookie name
223
     * @param Cookie $cookie the cookie to be added
224
     */
225
    public function offsetSet($name, $cookie)
226
    {
227
        $this->add($cookie);
228
    }
229
230
    /**
231
     * Removes the named cookie.
232
     * This method is required by the SPL interface [[\ArrayAccess]].
233
     * It is implicitly called when you use something like `unset($collection[$name])`.
234
     * This is equivalent to [[remove()]].
235
     * @param string $name the cookie name
236
     */
237
    public function offsetUnset($name)
238
    {
239
        $this->remove($name);
240
    }
241
}
242