CookieCollection.php 8.6 KB

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