vendor/symfony/http-foundation/Cookie.php line 19

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\HttpFoundation;
  11. /**
  12.  * Represents a cookie.
  13.  *
  14.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  15.  */
  16. class Cookie
  17. {
  18.     public const SAMESITE_NONE 'none';
  19.     public const SAMESITE_LAX 'lax';
  20.     public const SAMESITE_STRICT 'strict';
  21.     protected $name;
  22.     protected $value;
  23.     protected $domain;
  24.     protected $expire;
  25.     protected $path;
  26.     protected $secure;
  27.     protected $httpOnly;
  28.     private $raw;
  29.     private $sameSite;
  30.     private $secureDefault false;
  31.     private const RESERVED_CHARS_LIST "=,; \t\r\n\v\f";
  32.     private const RESERVED_CHARS_FROM = ['='','';'' '"\t""\r""\n""\v""\f"];
  33.     private const RESERVED_CHARS_TO = ['%3D''%2C''%3B''%20''%09''%0D''%0A''%0B''%0C'];
  34.     /**
  35.      * Creates cookie from raw header string.
  36.      *
  37.      * @return static
  38.      */
  39.     public static function fromString(string $cookiebool $decode false)
  40.     {
  41.         $data = [
  42.             'expires' => 0,
  43.             'path' => '/',
  44.             'domain' => null,
  45.             'secure' => false,
  46.             'httponly' => false,
  47.             'raw' => !$decode,
  48.             'samesite' => null,
  49.         ];
  50.         $parts HeaderUtils::split($cookie';=');
  51.         $part array_shift($parts);
  52.         $name $decode urldecode($part[0]) : $part[0];
  53.         $value = isset($part[1]) ? ($decode urldecode($part[1]) : $part[1]) : null;
  54.         $data HeaderUtils::combine($parts) + $data;
  55.         $data['expires'] = self::expiresTimestamp($data['expires']);
  56.         if (isset($data['max-age']) && ($data['max-age'] > || $data['expires'] > time())) {
  57.             $data['expires'] = time() + (int) $data['max-age'];
  58.         }
  59.         return new static($name$value$data['expires'], $data['path'], $data['domain'], $data['secure'], $data['httponly'], $data['raw'], $data['samesite']);
  60.     }
  61.     public static function create(string $namestring $value null$expire 0, ?string $path '/'string $domain nullbool $secure nullbool $httpOnly truebool $raw false, ?string $sameSite self::SAMESITE_LAX): self
  62.     {
  63.         return new self($name$value$expire$path$domain$secure$httpOnly$raw$sameSite);
  64.     }
  65.     /**
  66.      * @param string                        $name     The name of the cookie
  67.      * @param string|null                   $value    The value of the cookie
  68.      * @param int|string|\DateTimeInterface $expire   The time the cookie expires
  69.      * @param string                        $path     The path on the server in which the cookie will be available on
  70.      * @param string|null                   $domain   The domain that the cookie is available to
  71.      * @param bool|null                     $secure   Whether the client should send back the cookie only over HTTPS or null to auto-enable this when the request is already using HTTPS
  72.      * @param bool                          $httpOnly Whether the cookie will be made accessible only through the HTTP protocol
  73.      * @param bool                          $raw      Whether the cookie value should be sent with no url encoding
  74.      * @param string|null                   $sameSite Whether the cookie will be available for cross-site requests
  75.      *
  76.      * @throws \InvalidArgumentException
  77.      */
  78.     public function __construct(string $namestring $value null$expire 0, ?string $path '/'string $domain nullbool $secure nullbool $httpOnly truebool $raw false, ?string $sameSite 'lax')
  79.     {
  80.         // from PHP source code
  81.         if ($raw && false !== strpbrk($nameself::RESERVED_CHARS_LIST)) {
  82.             throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.'$name));
  83.         }
  84.         if (empty($name)) {
  85.             throw new \InvalidArgumentException('The cookie name cannot be empty.');
  86.         }
  87.         $this->name $name;
  88.         $this->value $value;
  89.         $this->domain $domain;
  90.         $this->expire self::expiresTimestamp($expire);
  91.         $this->path = empty($path) ? '/' $path;
  92.         $this->secure $secure;
  93.         $this->httpOnly $httpOnly;
  94.         $this->raw $raw;
  95.         $this->sameSite $this->withSameSite($sameSite)->sameSite;
  96.     }
  97.     /**
  98.      * Creates a cookie copy with a new value.
  99.      *
  100.      * @return static
  101.      */
  102.     public function withValue(?string $value): self
  103.     {
  104.         $cookie = clone $this;
  105.         $cookie->value $value;
  106.         return $cookie;
  107.     }
  108.     /**
  109.      * Creates a cookie copy with a new domain that the cookie is available to.
  110.      *
  111.      * @return static
  112.      */
  113.     public function withDomain(?string $domain): self
  114.     {
  115.         $cookie = clone $this;
  116.         $cookie->domain $domain;
  117.         return $cookie;
  118.     }
  119.     /**
  120.      * Creates a cookie copy with a new time the cookie expires.
  121.      *
  122.      * @param int|string|\DateTimeInterface $expire
  123.      *
  124.      * @return static
  125.      */
  126.     public function withExpires($expire 0): self
  127.     {
  128.         $cookie = clone $this;
  129.         $cookie->expire self::expiresTimestamp($expire);
  130.         return $cookie;
  131.     }
  132.     /**
  133.      * Converts expires formats to a unix timestamp.
  134.      *
  135.      * @param int|string|\DateTimeInterface $expire
  136.      */
  137.     private static function expiresTimestamp($expire 0): int
  138.     {
  139.         // convert expiration time to a Unix timestamp
  140.         if ($expire instanceof \DateTimeInterface) {
  141.             $expire $expire->format('U');
  142.         } elseif (!is_numeric($expire)) {
  143.             $expire strtotime($expire);
  144.             if (false === $expire) {
  145.                 throw new \InvalidArgumentException('The cookie expiration time is not valid.');
  146.             }
  147.         }
  148.         return $expire ? (int) $expire 0;
  149.     }
  150.     /**
  151.      * Creates a cookie copy with a new path on the server in which the cookie will be available on.
  152.      *
  153.      * @return static
  154.      */
  155.     public function withPath(string $path): self
  156.     {
  157.         $cookie = clone $this;
  158.         $cookie->path '' === $path '/' $path;
  159.         return $cookie;
  160.     }
  161.     /**
  162.      * Creates a cookie copy that only be transmitted over a secure HTTPS connection from the client.
  163.      *
  164.      * @return static
  165.      */
  166.     public function withSecure(bool $secure true): self
  167.     {
  168.         $cookie = clone $this;
  169.         $cookie->secure $secure;
  170.         return $cookie;
  171.     }
  172.     /**
  173.      * Creates a cookie copy that be accessible only through the HTTP protocol.
  174.      *
  175.      * @return static
  176.      */
  177.     public function withHttpOnly(bool $httpOnly true): self
  178.     {
  179.         $cookie = clone $this;
  180.         $cookie->httpOnly $httpOnly;
  181.         return $cookie;
  182.     }
  183.     /**
  184.      * Creates a cookie copy that uses no url encoding.
  185.      *
  186.      * @return static
  187.      */
  188.     public function withRaw(bool $raw true): self
  189.     {
  190.         if ($raw && false !== strpbrk($this->nameself::RESERVED_CHARS_LIST)) {
  191.             throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.'$this->name));
  192.         }
  193.         $cookie = clone $this;
  194.         $cookie->raw $raw;
  195.         return $cookie;
  196.     }
  197.     /**
  198.      * Creates a cookie copy with SameSite attribute.
  199.      *
  200.      * @return static
  201.      */
  202.     public function withSameSite(?string $sameSite): self
  203.     {
  204.         if ('' === $sameSite) {
  205.             $sameSite null;
  206.         } elseif (null !== $sameSite) {
  207.             $sameSite strtolower($sameSite);
  208.         }
  209.         if (!\in_array($sameSite, [self::SAMESITE_LAXself::SAMESITE_STRICTself::SAMESITE_NONEnull], true)) {
  210.             throw new \InvalidArgumentException('The "sameSite" parameter value is not valid.');
  211.         }
  212.         $cookie = clone $this;
  213.         $cookie->sameSite $sameSite;
  214.         return $cookie;
  215.     }
  216.     /**
  217.      * Returns the cookie as a string.
  218.      *
  219.      * @return string
  220.      */
  221.     public function __toString()
  222.     {
  223.         if ($this->isRaw()) {
  224.             $str $this->getName();
  225.         } else {
  226.             $str str_replace(self::RESERVED_CHARS_FROMself::RESERVED_CHARS_TO$this->getName());
  227.         }
  228.         $str .= '=';
  229.         if ('' === (string) $this->getValue()) {
  230.             $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T'time() - 31536001).'; Max-Age=0';
  231.         } else {
  232.             $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
  233.             if (!== $this->getExpiresTime()) {
  234.                 $str .= '; expires='.gmdate('D, d-M-Y H:i:s T'$this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
  235.             }
  236.         }
  237.         if ($this->getPath()) {
  238.             $str .= '; path='.$this->getPath();
  239.         }
  240.         if ($this->getDomain()) {
  241.             $str .= '; domain='.$this->getDomain();
  242.         }
  243.         if (true === $this->isSecure()) {
  244.             $str .= '; secure';
  245.         }
  246.         if (true === $this->isHttpOnly()) {
  247.             $str .= '; httponly';
  248.         }
  249.         if (null !== $this->getSameSite()) {
  250.             $str .= '; samesite='.$this->getSameSite();
  251.         }
  252.         return $str;
  253.     }
  254.     /**
  255.      * Gets the name of the cookie.
  256.      *
  257.      * @return string
  258.      */
  259.     public function getName()
  260.     {
  261.         return $this->name;
  262.     }
  263.     /**
  264.      * Gets the value of the cookie.
  265.      *
  266.      * @return string|null
  267.      */
  268.     public function getValue()
  269.     {
  270.         return $this->value;
  271.     }
  272.     /**
  273.      * Gets the domain that the cookie is available to.
  274.      *
  275.      * @return string|null
  276.      */
  277.     public function getDomain()
  278.     {
  279.         return $this->domain;
  280.     }
  281.     /**
  282.      * Gets the time the cookie expires.
  283.      *
  284.      * @return int
  285.      */
  286.     public function getExpiresTime()
  287.     {
  288.         return $this->expire;
  289.     }
  290.     /**
  291.      * Gets the max-age attribute.
  292.      *
  293.      * @return int
  294.      */
  295.     public function getMaxAge()
  296.     {
  297.         $maxAge $this->expire time();
  298.         return >= $maxAge $maxAge;
  299.     }
  300.     /**
  301.      * Gets the path on the server in which the cookie will be available on.
  302.      *
  303.      * @return string
  304.      */
  305.     public function getPath()
  306.     {
  307.         return $this->path;
  308.     }
  309.     /**
  310.      * Checks whether the cookie should only be transmitted over a secure HTTPS connection from the client.
  311.      *
  312.      * @return bool
  313.      */
  314.     public function isSecure()
  315.     {
  316.         return $this->secure ?? $this->secureDefault;
  317.     }
  318.     /**
  319.      * Checks whether the cookie will be made accessible only through the HTTP protocol.
  320.      *
  321.      * @return bool
  322.      */
  323.     public function isHttpOnly()
  324.     {
  325.         return $this->httpOnly;
  326.     }
  327.     /**
  328.      * Whether this cookie is about to be cleared.
  329.      *
  330.      * @return bool
  331.      */
  332.     public function isCleared()
  333.     {
  334.         return !== $this->expire && $this->expire time();
  335.     }
  336.     /**
  337.      * Checks if the cookie value should be sent with no url encoding.
  338.      *
  339.      * @return bool
  340.      */
  341.     public function isRaw()
  342.     {
  343.         return $this->raw;
  344.     }
  345.     /**
  346.      * Gets the SameSite attribute.
  347.      *
  348.      * @return string|null
  349.      */
  350.     public function getSameSite()
  351.     {
  352.         return $this->sameSite;
  353.     }
  354.     /**
  355.      * @param bool $default The default value of the "secure" flag when it is set to null
  356.      */
  357.     public function setSecureDefault(bool $default): void
  358.     {
  359.         $this->secureDefault $default;
  360.     }
  361. }