Completed
Push — master ( 9feb72...ff83a1 )
by Alexander
12:35
created

CookieCollection::has()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 5

Importance

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