Cookie.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\HttpMessage\Cookie;
  12. use DateTimeInterface;
  13. use InvalidArgumentException;
  14. use Stringable;
  15. class Cookie implements Stringable
  16. {
  17. public const SAMESITE_LAX = 'lax';
  18. public const SAMESITE_STRICT = 'strict';
  19. public const SAMESITE_NONE = 'none';
  20. protected int $expire;
  21. protected string $path;
  22. private ?string $sameSite = null;
  23. /**
  24. * @param string $name The name of the cookie
  25. * @param string $value The value of the cookie
  26. * @param DateTimeInterface|int|string $expire The time the cookie expires
  27. * @param string $path The path on the server in which the cookie will be available on
  28. * @param string $domain The domain that the cookie is available to
  29. * @param bool $secure Whether the cookie should only be transmitted over a secure HTTPS connection from the client
  30. * @param bool $httpOnly Whether the cookie will be made accessible only through the HTTP protocol
  31. * @param bool $raw Whether the cookie value should be sent with no url encoding
  32. * @param null|string $sameSite Whether the cookie will be available for cross-site requests
  33. *
  34. * @throws InvalidArgumentException
  35. */
  36. public function __construct(
  37. protected string $name,
  38. protected string $value = '',
  39. $expire = 0,
  40. string $path = '/',
  41. protected string $domain = '',
  42. protected bool $secure = false,
  43. protected bool $httpOnly = true,
  44. protected bool $raw = false,
  45. ?string $sameSite = null
  46. ) {
  47. // from PHP source code
  48. if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
  49. throw new InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
  50. }
  51. if (empty($name)) {
  52. throw new InvalidArgumentException('The cookie name cannot be empty.');
  53. }
  54. // convert expiration time to a Unix timestamp
  55. if ($expire instanceof DateTimeInterface) {
  56. $expire = $expire->format('U');
  57. } elseif (! is_numeric($expire)) {
  58. $expire = strtotime($expire);
  59. if ($expire === false) {
  60. throw new InvalidArgumentException('The cookie expiration time is not valid.');
  61. }
  62. }
  63. $this->expire = 0 < $expire ? (int) $expire : 0;
  64. $this->path = empty($path) ? '/' : $path;
  65. if ($sameSite !== null) {
  66. $sameSite = strtolower($sameSite);
  67. }
  68. if (! in_array($sameSite, [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE, null], true)) {
  69. throw new InvalidArgumentException('The "sameSite" parameter value is not valid.');
  70. }
  71. $this->sameSite = $sameSite;
  72. }
  73. /**
  74. * Returns the cookie as a string.
  75. *
  76. * @return string The cookie
  77. */
  78. public function __toString()
  79. {
  80. $str = ($this->isRaw() ? $this->getName() : urlencode($this->getName())) . '=';
  81. if ($this->getValue() === '') {
  82. $str .= 'deleted; expires=' . gmdate('D, d-M-Y H:i:s T', time() - 31536001) . '; max-age=-31536001';
  83. } else {
  84. $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
  85. if ($this->getExpiresTime() !== 0) {
  86. $str .= '; expires=' . gmdate(
  87. 'D, d-M-Y H:i:s T',
  88. $this->getExpiresTime()
  89. ) . '; max-age=' . $this->getMaxAge();
  90. }
  91. }
  92. if ($this->getPath()) {
  93. $str .= '; path=' . $this->getPath();
  94. }
  95. if ($this->getDomain()) {
  96. $str .= '; domain=' . $this->getDomain();
  97. }
  98. if ($this->isSecure() === true) {
  99. $str .= '; secure';
  100. }
  101. if ($this->isHttpOnly() === true) {
  102. $str .= '; httponly';
  103. }
  104. if ($this->getSameSite() !== null) {
  105. $str .= '; samesite=' . $this->getSameSite();
  106. }
  107. return $str;
  108. }
  109. /**
  110. * Creates cookie from raw header string.
  111. */
  112. public static function fromString(string $cookie, bool $decode = false): self
  113. {
  114. $data = [
  115. 'expires' => 0,
  116. 'path' => '/',
  117. 'domain' => '',
  118. 'secure' => false,
  119. 'httponly' => false,
  120. 'raw' => ! $decode,
  121. 'samesite' => null,
  122. ];
  123. foreach (explode(';', $cookie) as $part) {
  124. if (! str_contains($part, '=')) {
  125. $key = trim($part);
  126. $value = true;
  127. } else {
  128. [$key, $value] = explode('=', trim($part), 2);
  129. $key = trim($key);
  130. $value = trim($value);
  131. }
  132. if (! isset($data['name'])) {
  133. $data['name'] = $decode ? urldecode($key) : $key;
  134. $data['value'] = $value === true ? null : ($decode ? urldecode($value) : $value);
  135. continue;
  136. }
  137. switch ($key = strtolower($key)) {
  138. case 'name':
  139. case 'value':
  140. break;
  141. case 'max-age':
  142. $data['expires'] = time() + (int) $value;
  143. break;
  144. default:
  145. $data[$key] = $value;
  146. break;
  147. }
  148. }
  149. return new Cookie(
  150. $data['name'],
  151. $data['value'],
  152. $data['expires'],
  153. $data['path'],
  154. $data['domain'],
  155. $data['secure'],
  156. $data['httponly'],
  157. $data['raw'],
  158. $data['samesite']
  159. );
  160. }
  161. /**
  162. * Gets the name of the cookie.
  163. */
  164. public function getName(): string
  165. {
  166. return $this->name;
  167. }
  168. /**
  169. * Gets the value of the cookie.
  170. */
  171. public function getValue(): string
  172. {
  173. return $this->value;
  174. }
  175. /**
  176. * Gets the domain that the cookie is available to.
  177. */
  178. public function getDomain(): string
  179. {
  180. return $this->domain;
  181. }
  182. /**
  183. * Gets the time the cookie expires.
  184. */
  185. public function getExpiresTime(): int
  186. {
  187. return $this->expire;
  188. }
  189. /**
  190. * Gets the max-age attribute.
  191. */
  192. public function getMaxAge(): int
  193. {
  194. return $this->expire !== 0 ? $this->expire - time() : 0;
  195. }
  196. /**
  197. * Gets the path on the server in which the cookie will be available on.
  198. */
  199. public function getPath(): string
  200. {
  201. return $this->path;
  202. }
  203. /**
  204. * Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
  205. */
  206. public function isSecure(): bool
  207. {
  208. return $this->secure;
  209. }
  210. /**
  211. * Checks whether the cookie will be made accessible only through the HTTP protocol.
  212. */
  213. public function isHttpOnly(): bool
  214. {
  215. return $this->httpOnly;
  216. }
  217. /**
  218. * Whether this cookie is about to be cleared.
  219. */
  220. public function isCleared(): bool
  221. {
  222. return $this->expire < time();
  223. }
  224. /**
  225. * Checks if the cookie value should be sent with no url encoding.
  226. */
  227. public function isRaw(): bool
  228. {
  229. return $this->raw;
  230. }
  231. /**
  232. * Gets the SameSite attribute.
  233. */
  234. public function getSameSite(): ?string
  235. {
  236. return $this->sameSite;
  237. }
  238. }