SetCookie.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 Hyperf\Contract\Arrayable;
  13. use Stringable;
  14. /**
  15. * Set-Cookie object.
  16. */
  17. class SetCookie implements Stringable, Arrayable
  18. {
  19. private static array $defaults = [
  20. 'Name' => null,
  21. 'Value' => null,
  22. 'Domain' => null,
  23. 'Path' => '/',
  24. 'Max-Age' => null,
  25. 'Expires' => null,
  26. 'Secure' => false,
  27. 'Discard' => false,
  28. 'HttpOnly' => false,
  29. ];
  30. /**
  31. * Array of cookie data provided by a Cookie parser.
  32. */
  33. private array $data;
  34. /**
  35. * @param array $data Array of cookie data provided by a Cookie parser
  36. */
  37. public function __construct(array $data = [])
  38. {
  39. $this->data = array_replace(self::$defaults, $data);
  40. // Extract the Expires value and turn it into a UNIX timestamp if needed
  41. if (! $this->getExpires() && $this->getMaxAge()) {
  42. // Calculate the Expires date
  43. $this->setExpires(time() + $this->getMaxAge());
  44. } elseif ($this->getExpires() && ! is_numeric($this->getExpires())) {
  45. $this->setExpires($this->getExpires());
  46. }
  47. }
  48. public function __toString()
  49. {
  50. $str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';
  51. foreach ($this->data as $k => $v) {
  52. if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
  53. if ($k === 'Expires') {
  54. $str .= 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $v) . '; ';
  55. } else {
  56. $str .= ($v === true ? $k : "{$k}={$v}") . '; ';
  57. }
  58. }
  59. }
  60. return rtrim($str, '; ');
  61. }
  62. /**
  63. * Create a new SetCookie object from a string.
  64. *
  65. * @param string $cookie Set-Cookie header string
  66. */
  67. public static function fromString(string $cookie): self
  68. {
  69. // Create the default return array
  70. $data = self::$defaults;
  71. // Explode the cookie string using a series of semicolons
  72. $pieces = array_filter(array_map('trim', explode(';', $cookie)));
  73. // The name of the cookie (first kvp) must include an equal sign.
  74. if (empty($pieces) || ! strpos($pieces[0], '=')) {
  75. return new self($data);
  76. }
  77. // Add the cookie pieces into the parsed data array
  78. foreach ($pieces as $part) {
  79. $cookieParts = explode('=', $part, 2);
  80. $key = trim($cookieParts[0]);
  81. $value = isset($cookieParts[1])
  82. ? trim($cookieParts[1], " \n\r\t\0\x0B")
  83. : true;
  84. // Only check for non-cookies when cookies have been found
  85. if (empty($data['Name'])) {
  86. $data['Name'] = $key;
  87. $data['Value'] = $value;
  88. } else {
  89. foreach (array_keys(self::$defaults) as $search) {
  90. if (! strcasecmp($search, $key)) {
  91. $data[$search] = $value;
  92. continue 2;
  93. }
  94. }
  95. $data[$key] = $value;
  96. }
  97. }
  98. return new self($data);
  99. }
  100. public function toArray(): array
  101. {
  102. return $this->data;
  103. }
  104. /**
  105. * Get the cookie name.
  106. */
  107. public function getName(): ?string
  108. {
  109. return $this->data['Name'];
  110. }
  111. /**
  112. * Set the cookie name.
  113. *
  114. * @param string $name Cookie name
  115. */
  116. public function setName(?string $name)
  117. {
  118. $this->data['Name'] = $name;
  119. }
  120. /**
  121. * Get the cookie value.
  122. */
  123. public function getValue(): ?string
  124. {
  125. return $this->data['Value'];
  126. }
  127. /**
  128. * Set the cookie value.
  129. *
  130. * @param null|string $value Cookie value
  131. */
  132. public function setValue(?string $value)
  133. {
  134. $this->data['Value'] = $value;
  135. }
  136. /**
  137. * Get the domain.
  138. */
  139. public function getDomain(): ?string
  140. {
  141. return $this->data['Domain'];
  142. }
  143. /**
  144. * Set the domain of the cookie.
  145. */
  146. public function setDomain(?string $domain)
  147. {
  148. $this->data['Domain'] = $domain;
  149. }
  150. /**
  151. * Get the path.
  152. */
  153. public function getPath(): string
  154. {
  155. return $this->data['Path'];
  156. }
  157. /**
  158. * Set the path of the cookie.
  159. *
  160. * @param string $path Path of the cookie
  161. */
  162. public function setPath(string $path)
  163. {
  164. $this->data['Path'] = $path;
  165. }
  166. /**
  167. * Maximum lifetime of the cookie in seconds.
  168. */
  169. public function getMaxAge(): ?int
  170. {
  171. return $this->data['Max-Age'];
  172. }
  173. /**
  174. * Set the max-age of the cookie.
  175. *
  176. * @param null|int $maxAge Max age of the cookie in seconds
  177. */
  178. public function setMaxAge(?int $maxAge)
  179. {
  180. $this->data['Max-Age'] = $maxAge;
  181. }
  182. /**
  183. * The UNIX timestamp when the cookie Expires.
  184. *
  185. * @return int|string
  186. */
  187. public function getExpires()
  188. {
  189. return $this->data['Expires'];
  190. }
  191. /**
  192. * Set the unix timestamp for which the cookie will expire.
  193. *
  194. * @param float|int|string $timestamp Unix timestamp
  195. */
  196. public function setExpires($timestamp)
  197. {
  198. $this->data['Expires'] = is_numeric($timestamp)
  199. ? (int) $timestamp
  200. : strtotime($timestamp);
  201. }
  202. /**
  203. * Get whether this is a secure cookie.
  204. */
  205. public function getSecure(): bool
  206. {
  207. return $this->data['Secure'];
  208. }
  209. /**
  210. * Set whether the cookie is secure.
  211. *
  212. * @param bool $secure Set to true or false if secure
  213. */
  214. public function setSecure(bool $secure)
  215. {
  216. $this->data['Secure'] = $secure;
  217. }
  218. /**
  219. * Get whether this is a session cookie.
  220. */
  221. public function getDiscard(): bool
  222. {
  223. return $this->data['Discard'];
  224. }
  225. /**
  226. * Set whether this is a session cookie.
  227. *
  228. * @param bool $discard Set to true or false if this is a session cookie
  229. */
  230. public function setDiscard(bool $discard)
  231. {
  232. $this->data['Discard'] = $discard;
  233. }
  234. /**
  235. * Get whether this is an HTTP only cookie.
  236. */
  237. public function getHttpOnly(): bool
  238. {
  239. return $this->data['HttpOnly'];
  240. }
  241. /**
  242. * Set whether this is an HTTP only cookie.
  243. *
  244. * @param bool $httpOnly Set to true or false if this is HTTP only
  245. */
  246. public function setHttpOnly(bool $httpOnly)
  247. {
  248. $this->data['HttpOnly'] = $httpOnly;
  249. }
  250. /**
  251. * Check if the cookie matches a path value.
  252. *
  253. * A request-path path-matches a given cookie-path if at least one of
  254. * the following conditions holds:
  255. *
  256. * - The cookie-path and the request-path are identical.
  257. * - The cookie-path is a prefix of the request-path, and the last
  258. * character of the cookie-path is %x2F ("/").
  259. * - The cookie-path is a prefix of the request-path, and the first
  260. * character of the request-path that is not included in the cookie-
  261. * path is a %x2F ("/") character.
  262. *
  263. * @param string $requestPath Path to check against
  264. */
  265. public function matchesPath(string $requestPath): bool
  266. {
  267. $cookiePath = $this->getPath();
  268. // Match on exact matches or when path is the default empty "/"
  269. if ($cookiePath === '/' || $cookiePath == $requestPath) {
  270. return true;
  271. }
  272. // Ensure that the cookie-path is a prefix of the request path.
  273. if (! str_starts_with($requestPath, $cookiePath)) {
  274. return false;
  275. }
  276. // Match if the last character of the cookie-path is "/"
  277. if (substr($cookiePath, -1, 1) === '/') {
  278. return true;
  279. }
  280. // Match if the first character not included in cookie path is "/"
  281. return substr($requestPath, strlen($cookiePath), 1) === '/';
  282. }
  283. /**
  284. * Check if the cookie matches a domain value.
  285. *
  286. * @param string $domain Domain to check against
  287. */
  288. public function matchesDomain(string $domain): bool
  289. {
  290. // Remove the leading '.' as per spec in RFC 6265.
  291. // http://tools.ietf.org/html/rfc6265#section-5.2.3
  292. $cookieDomain = ltrim($this->getDomain(), '.');
  293. // Domain not set or exact match.
  294. if (! $cookieDomain || ! strcasecmp($domain, $cookieDomain)) {
  295. return true;
  296. }
  297. // Matching the subdomain according to RFC 6265.
  298. // http://tools.ietf.org/html/rfc6265#section-5.1.3
  299. if (filter_var($domain, FILTER_VALIDATE_IP)) {
  300. return false;
  301. }
  302. return (bool) preg_match('/\.' . preg_quote($cookieDomain) . '$/', $domain);
  303. }
  304. /**
  305. * Check if the cookie is expired.
  306. */
  307. public function isExpired(): bool
  308. {
  309. return $this->getExpires() && time() > $this->getExpires();
  310. }
  311. /**
  312. * Check if the cookie is valid according to RFC 6265.
  313. *
  314. * @return bool|string Returns true if valid or an error message if invalid
  315. */
  316. public function validate(): bool|string
  317. {
  318. // Names must not be empty, but can be 0
  319. $name = $this->getName();
  320. if (empty($name) && ! is_numeric($name)) {
  321. return 'The cookie name must not be empty';
  322. }
  323. // Check if any of the invalid characters are present in the cookie name
  324. if (preg_match(
  325. '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
  326. $name
  327. )
  328. ) {
  329. return 'Cookie name must not contain invalid characters: ASCII '
  330. . 'Control characters (0-31;127), space, tab and the '
  331. . 'following characters: ()<>@,;:\"/?={}';
  332. }
  333. // Value must not be empty, but can be 0
  334. $value = $this->getValue();
  335. if (empty($value) && ! is_numeric($value)) {
  336. return 'The cookie value must not be empty';
  337. }
  338. // Domains must not be empty, but can be 0
  339. // A "0" is not a valid internet domain, but may be used as server name
  340. // in a private network.
  341. $domain = $this->getDomain();
  342. if (empty($domain) && ! is_numeric($domain)) {
  343. return 'The cookie domain must not be empty';
  344. }
  345. return true;
  346. }
  347. }