CookieCollection.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class CookieCollection extends BaseObject implements \IteratorAggregate, \ArrayAccess, \Countable
  23. {
  24. /**
  25. * @var bool whether this collection is read only.
  26. */
  27. public $readOnly = false;
  28. /**
  29. * @var Cookie[] the cookies in this collection (indexed by the cookie names)
  30. */
  31. private $_cookies;
  32. /**
  33. * Constructor.
  34. * @param array $cookies the cookies that this collection initially contains. This should be
  35. * an array of name-value pairs.
  36. * @param array $config name-value pairs that will be used to initialize the object properties
  37. */
  38. public function __construct($cookies = [], $config = [])
  39. {
  40. $this->_cookies = $cookies;
  41. parent::__construct($config);
  42. }
  43. /**
  44. * Returns an iterator for traversing the cookies in the collection.
  45. * This method is required by the SPL interface [[\IteratorAggregate]].
  46. * It will be implicitly called when you use `foreach` to traverse the collection.
  47. * @return ArrayIterator<string, Cookie> an iterator for traversing the cookies in the collection.
  48. */
  49. #[\ReturnTypeWillChange]
  50. public function getIterator()
  51. {
  52. return new ArrayIterator($this->_cookies);
  53. }
  54. /**
  55. * Returns the number of cookies in the collection.
  56. * This method is required by the SPL `Countable` interface.
  57. * It will be implicitly called when you use `count($collection)`.
  58. * @return int the number of cookies in the collection.
  59. */
  60. #[\ReturnTypeWillChange]
  61. public function count()
  62. {
  63. return $this->getCount();
  64. }
  65. /**
  66. * Returns the number of cookies in the collection.
  67. * @return int the number of cookies in the collection.
  68. */
  69. public function getCount()
  70. {
  71. return count($this->_cookies);
  72. }
  73. /**
  74. * Returns the cookie with the specified name.
  75. * @param string $name the cookie name
  76. * @return Cookie|null the cookie with the specified name. Null if the named cookie does not exist.
  77. * @see getValue()
  78. */
  79. public function get($name)
  80. {
  81. return isset($this->_cookies[$name]) ? $this->_cookies[$name] : null;
  82. }
  83. /**
  84. * Returns the value of the named cookie.
  85. * @param string $name the cookie name
  86. * @param mixed $defaultValue the value that should be returned when the named cookie does not exist.
  87. * @return mixed the value of the named cookie.
  88. * @see get()
  89. */
  90. public function getValue($name, $defaultValue = null)
  91. {
  92. return isset($this->_cookies[$name]) ? $this->_cookies[$name]->value : $defaultValue;
  93. }
  94. /**
  95. * Returns whether there is a cookie with the specified name.
  96. * Note that if a cookie is marked for deletion from browser or its value is an empty string, this method will return false.
  97. * @param string $name the cookie name
  98. * @return bool whether the named cookie exists
  99. * @see remove()
  100. */
  101. public function has($name)
  102. {
  103. return isset($this->_cookies[$name]) && $this->_cookies[$name]->value !== ''
  104. && ($this->_cookies[$name]->expire === null
  105. || $this->_cookies[$name]->expire === 0
  106. || (
  107. (is_string($this->_cookies[$name]->expire) && strtotime($this->_cookies[$name]->expire) >= time())
  108. || (
  109. interface_exists('\\DateTimeInterface')
  110. && $this->_cookies[$name]->expire instanceof \DateTimeInterface
  111. && $this->_cookies[$name]->expire->getTimestamp() >= time()
  112. )
  113. || $this->_cookies[$name]->expire >= time()
  114. )
  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. * Removes a cookie.
  132. * If `$removeFromBrowser` is true, the cookie will be removed from the browser.
  133. * In this case, a cookie with outdated expiry will be added to the collection.
  134. * @param Cookie|string $cookie the cookie object or the name of the cookie to be removed.
  135. * @param bool $removeFromBrowser whether to remove the cookie from browser
  136. * @throws InvalidCallException if the cookie collection is read only
  137. */
  138. public function remove($cookie, $removeFromBrowser = true)
  139. {
  140. if ($this->readOnly) {
  141. throw new InvalidCallException('The cookie collection is read only.');
  142. }
  143. if ($cookie instanceof Cookie) {
  144. $cookie->expire = 1;
  145. $cookie->value = '';
  146. } else {
  147. $cookie = Yii::createObject([
  148. 'class' => 'yii\web\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. * Removes all cookies.
  161. * @throws InvalidCallException if the cookie collection is read only
  162. */
  163. public function removeAll()
  164. {
  165. if ($this->readOnly) {
  166. throw new InvalidCallException('The cookie collection is read only.');
  167. }
  168. $this->_cookies = [];
  169. }
  170. /**
  171. * Returns the collection as a PHP array.
  172. * @return Cookie[] the array representation of the collection.
  173. * The array keys are cookie names, and the array values are the corresponding cookie objects.
  174. */
  175. public function toArray()
  176. {
  177. return $this->_cookies;
  178. }
  179. /**
  180. * Populates the cookie collection from an array.
  181. * @param array $array the cookies to populate from
  182. * @since 2.0.3
  183. */
  184. public function fromArray(array $array)
  185. {
  186. $this->_cookies = $array;
  187. }
  188. /**
  189. * Returns whether there is a cookie with the specified name.
  190. * This method is required by the SPL interface [[\ArrayAccess]].
  191. * It is implicitly called when you use something like `isset($collection[$name])`.
  192. * @param string $name the cookie name
  193. * @return bool whether the named cookie exists
  194. */
  195. #[\ReturnTypeWillChange]
  196. public function offsetExists($name)
  197. {
  198. return $this->has($name);
  199. }
  200. /**
  201. * Returns the cookie with the specified name.
  202. * This method is required by the SPL interface [[\ArrayAccess]].
  203. * It is implicitly called when you use something like `$cookie = $collection[$name];`.
  204. * This is equivalent to [[get()]].
  205. * @param string $name the cookie name
  206. * @return Cookie|null the cookie with the specified name, null if the named cookie does not exist.
  207. */
  208. #[\ReturnTypeWillChange]
  209. public function offsetGet($name)
  210. {
  211. return $this->get($name);
  212. }
  213. /**
  214. * Adds the cookie to the collection.
  215. * This method is required by the SPL interface [[\ArrayAccess]].
  216. * It is implicitly called when you use something like `$collection[$name] = $cookie;`.
  217. * This is equivalent to [[add()]].
  218. * @param string $name the cookie name
  219. * @param Cookie $cookie the cookie to be added
  220. */
  221. #[\ReturnTypeWillChange]
  222. public function offsetSet($name, $cookie)
  223. {
  224. $this->add($cookie);
  225. }
  226. /**
  227. * Removes the named cookie.
  228. * This method is required by the SPL interface [[\ArrayAccess]].
  229. * It is implicitly called when you use something like `unset($collection[$name])`.
  230. * This is equivalent to [[remove()]].
  231. * @param string $name the cookie name
  232. */
  233. #[\ReturnTypeWillChange]
  234. public function offsetUnset($name)
  235. {
  236. $this->remove($name);
  237. }
  238. }