Issues (836)

framework/web/CookieCollection.php (2 issues)

Labels
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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-read int $count The number of cookies in the collection.
21
 * @property-read ArrayIterator $iterator An iterator for traversing the cookies in the collection.
22
 *
23
 * @author Qiang Xue <[email protected]>
24
 * @since 2.0
25
 */
26
class CookieCollection extends BaseObject implements \IteratorAggregate, \ArrayAccess, \Countable
27
{
28
    /**
29
     * @var bool whether this collection is read only.
30
     */
31
    public $readOnly = false;
32
33
    /**
34
     * @var Cookie[] the cookies in this collection (indexed by the cookie names)
35
     */
36
    private $_cookies;
37
38
39
    /**
40
     * Constructor.
41
     * @param array $cookies the cookies that this collection initially contains. This should be
42
     * an array of name-value pairs.
43
     * @param array $config name-value pairs that will be used to initialize the object properties
44
     */
45 93
    public function __construct($cookies = [], $config = [])
46
    {
47 93
        $this->_cookies = $cookies;
48 93
        parent::__construct($config);
49
    }
50
51
    /**
52
     * Returns an iterator for traversing the cookies in the collection.
53
     * This method is required by the SPL interface [[\IteratorAggregate]].
54
     * It will be implicitly called when you use `foreach` to traverse the collection.
55
     * @return ArrayIterator<string, Cookie> an iterator for traversing the cookies in the collection.
56
     */
57 9
    #[\ReturnTypeWillChange]
58
    public function getIterator()
59
    {
60 9
        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
    #[\ReturnTypeWillChange]
70
    public function count()
71
    {
72
        return $this->getCount();
73
    }
74
75
    /**
76
     * Returns the number of cookies in the collection.
77
     * @return int the number of cookies in the collection.
78
     */
79
    public function getCount()
80
    {
81
        return count($this->_cookies);
82
    }
83
84
    /**
85
     * Returns the cookie with the specified name.
86
     * @param string $name the cookie name
87
     * @return Cookie|null the cookie with the specified name. Null if the named cookie does not exist.
88
     * @see getValue()
89
     */
90
    public function get($name)
91
    {
92
        return isset($this->_cookies[$name]) ? $this->_cookies[$name] : null;
93
    }
94
95
    /**
96
     * Returns the value of the named cookie.
97
     * @param string $name the cookie name
98
     * @param mixed $defaultValue the value that should be returned when the named cookie does not exist.
99
     * @return mixed the value of the named cookie.
100
     * @see get()
101
     */
102 87
    public function getValue($name, $defaultValue = null)
103
    {
104 87
        return isset($this->_cookies[$name]) ? $this->_cookies[$name]->value : $defaultValue;
105
    }
106
107
    /**
108
     * Returns whether there is a cookie with the specified name.
109
     * Note that if a cookie is marked for deletion from browser or its value is an empty string, this method will return false.
110
     * @param string $name the cookie name
111
     * @return bool whether the named cookie exists
112
     * @see remove()
113
     */
114 4
    public function has($name)
115
    {
116 4
        return isset($this->_cookies[$name]) && $this->_cookies[$name]->value !== ''
117 4
            && ($this->_cookies[$name]->expire === null
118 4
                || $this->_cookies[$name]->expire === 0
119 4
                || (
120 4
                    (is_string($this->_cookies[$name]->expire) && strtotime($this->_cookies[$name]->expire) >= time())
0 ignored issues
show
It seems like $this->_cookies[$name]->expire can also be of type DateTimeInterface and null; however, parameter $datetime of strtotime() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

120
                    (is_string($this->_cookies[$name]->expire) && strtotime(/** @scrutinizer ignore-type */ $this->_cookies[$name]->expire) >= time())
Loading history...
121 4
                    || (
122 4
                        interface_exists('\\DateTimeInterface')
123 4
                        && $this->_cookies[$name]->expire instanceof \DateTimeInterface
124 4
                        && $this->_cookies[$name]->expire->getTimestamp() >= time()
0 ignored issues
show
The method getTimestamp() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

124
                        && $this->_cookies[$name]->expire->/** @scrutinizer ignore-call */ getTimestamp() >= time()

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
125 4
                    )
126 4
                    || $this->_cookies[$name]->expire >= time()
127 4
                )
128 4
            );
129
    }
130
131
    /**
132
     * Adds a cookie to the collection.
133
     * If there is already a cookie with the same name in the collection, it will be removed first.
134
     * @param Cookie $cookie the cookie to be added
135
     * @throws InvalidCallException if the cookie collection is read only
136
     */
137 93
    public function add($cookie)
138
    {
139 93
        if ($this->readOnly) {
140
            throw new InvalidCallException('The cookie collection is read only.');
141
        }
142 93
        $this->_cookies[$cookie->name] = $cookie;
143
    }
144
145
    /**
146
     * Removes a cookie.
147
     * If `$removeFromBrowser` is true, the cookie will be removed from the browser.
148
     * In this case, a cookie with outdated expiry will be added to the collection.
149
     * @param Cookie|string $cookie the cookie object or the name of the cookie to be removed.
150
     * @param bool $removeFromBrowser whether to remove the cookie from browser
151
     * @throws InvalidCallException if the cookie collection is read only
152
     */
153 2
    public function remove($cookie, $removeFromBrowser = true)
154
    {
155 2
        if ($this->readOnly) {
156
            throw new InvalidCallException('The cookie collection is read only.');
157
        }
158 2
        if ($cookie instanceof Cookie) {
159 2
            $cookie->expire = 1;
160 2
            $cookie->value = '';
161
        } else {
162
            $cookie = Yii::createObject([
163
                'class' => 'yii\web\Cookie',
164
                'name' => $cookie,
165
                'expire' => 1,
166
            ]);
167
        }
168 2
        if ($removeFromBrowser) {
169 2
            $this->_cookies[$cookie->name] = $cookie;
170
        } else {
171
            unset($this->_cookies[$cookie->name]);
172
        }
173
    }
174
175
    /**
176
     * Removes all cookies.
177
     * @throws InvalidCallException if the cookie collection is read only
178
     */
179
    public function removeAll()
180
    {
181
        if ($this->readOnly) {
182
            throw new InvalidCallException('The cookie collection is read only.');
183
        }
184
        $this->_cookies = [];
185
    }
186
187
    /**
188
     * Returns the collection as a PHP array.
189
     * @return Cookie[] the array representation of the collection.
190
     * The array keys are cookie names, and the array values are the corresponding cookie objects.
191
     */
192 3
    public function toArray()
193
    {
194 3
        return $this->_cookies;
195
    }
196
197
    /**
198
     * Populates the cookie collection from an array.
199
     * @param array $array the cookies to populate from
200
     * @since 2.0.3
201
     */
202 3
    public function fromArray(array $array)
203
    {
204 3
        $this->_cookies = $array;
205
    }
206
207
    /**
208
     * Returns whether there is a 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 `isset($collection[$name])`.
211
     * @param string $name the cookie name
212
     * @return bool whether the named cookie exists
213
     */
214
    #[\ReturnTypeWillChange]
215
    public function offsetExists($name)
216
    {
217
        return $this->has($name);
218
    }
219
220
    /**
221
     * Returns the cookie with the specified name.
222
     * This method is required by the SPL interface [[\ArrayAccess]].
223
     * It is implicitly called when you use something like `$cookie = $collection[$name];`.
224
     * This is equivalent to [[get()]].
225
     * @param string $name the cookie name
226
     * @return Cookie|null the cookie with the specified name, null if the named cookie does not exist.
227
     */
228
    #[\ReturnTypeWillChange]
229
    public function offsetGet($name)
230
    {
231
        return $this->get($name);
232
    }
233
234
    /**
235
     * Adds the cookie to the collection.
236
     * This method is required by the SPL interface [[\ArrayAccess]].
237
     * It is implicitly called when you use something like `$collection[$name] = $cookie;`.
238
     * This is equivalent to [[add()]].
239
     * @param string $name the cookie name
240
     * @param Cookie $cookie the cookie to be added
241
     */
242
    #[\ReturnTypeWillChange]
243
    public function offsetSet($name, $cookie)
244
    {
245
        $this->add($cookie);
246
    }
247
248
    /**
249
     * Removes the named cookie.
250
     * This method is required by the SPL interface [[\ArrayAccess]].
251
     * It is implicitly called when you use something like `unset($collection[$name])`.
252
     * This is equivalent to [[remove()]].
253
     * @param string $name the cookie name
254
     */
255
    #[\ReturnTypeWillChange]
256
    public function offsetUnset($name)
257
    {
258
        $this->remove($name);
259
    }
260
}
261