vendor/symfony/http-foundation/Request.php line 773

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. use Symfony\Component\HttpFoundation\Exception\BadRequestException;
  12. use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
  13. use Symfony\Component\HttpFoundation\Exception\JsonException;
  14. use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
  15. use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
  16. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  17. // Help opcache.preload discover always-needed symbols
  18. class_exists(AcceptHeader::class);
  19. class_exists(FileBag::class);
  20. class_exists(HeaderBag::class);
  21. class_exists(HeaderUtils::class);
  22. class_exists(InputBag::class);
  23. class_exists(ParameterBag::class);
  24. class_exists(ServerBag::class);
  25. /**
  26.  * Request represents an HTTP request.
  27.  *
  28.  * The methods dealing with URL accept / return a raw path (% encoded):
  29.  *   * getBasePath
  30.  *   * getBaseUrl
  31.  *   * getPathInfo
  32.  *   * getRequestUri
  33.  *   * getUri
  34.  *   * getUriForPath
  35.  *
  36.  * @author Fabien Potencier <fabien@symfony.com>
  37.  */
  38. class Request
  39. {
  40.     public const HEADER_FORWARDED 0b000001// When using RFC 7239
  41.     public const HEADER_X_FORWARDED_FOR 0b000010;
  42.     public const HEADER_X_FORWARDED_HOST 0b000100;
  43.     public const HEADER_X_FORWARDED_PROTO 0b001000;
  44.     public const HEADER_X_FORWARDED_PORT 0b010000;
  45.     public const HEADER_X_FORWARDED_PREFIX 0b100000;
  46.     public const HEADER_X_FORWARDED_AWS_ELB 0b0011010// AWS ELB doesn't send X-Forwarded-Host
  47.     public const HEADER_X_FORWARDED_TRAEFIK 0b0111110// All "X-Forwarded-*" headers sent by Traefik reverse proxy
  48.     public const METHOD_HEAD 'HEAD';
  49.     public const METHOD_GET 'GET';
  50.     public const METHOD_POST 'POST';
  51.     public const METHOD_PUT 'PUT';
  52.     public const METHOD_PATCH 'PATCH';
  53.     public const METHOD_DELETE 'DELETE';
  54.     public const METHOD_PURGE 'PURGE';
  55.     public const METHOD_OPTIONS 'OPTIONS';
  56.     public const METHOD_TRACE 'TRACE';
  57.     public const METHOD_CONNECT 'CONNECT';
  58.     /**
  59.      * @var string[]
  60.      */
  61.     protected static $trustedProxies = [];
  62.     /**
  63.      * @var string[]
  64.      */
  65.     protected static $trustedHostPatterns = [];
  66.     /**
  67.      * @var string[]
  68.      */
  69.     protected static $trustedHosts = [];
  70.     protected static $httpMethodParameterOverride false;
  71.     /**
  72.      * Custom parameters.
  73.      *
  74.      * @var ParameterBag
  75.      */
  76.     public $attributes;
  77.     /**
  78.      * Request body parameters ($_POST).
  79.      *
  80.      * @see getPayload() for portability between content types
  81.      *
  82.      * @var InputBag
  83.      */
  84.     public $request;
  85.     /**
  86.      * Query string parameters ($_GET).
  87.      *
  88.      * @var InputBag
  89.      */
  90.     public $query;
  91.     /**
  92.      * Server and execution environment parameters ($_SERVER).
  93.      *
  94.      * @var ServerBag
  95.      */
  96.     public $server;
  97.     /**
  98.      * Uploaded files ($_FILES).
  99.      *
  100.      * @var FileBag
  101.      */
  102.     public $files;
  103.     /**
  104.      * Cookies ($_COOKIE).
  105.      *
  106.      * @var InputBag
  107.      */
  108.     public $cookies;
  109.     /**
  110.      * Headers (taken from the $_SERVER).
  111.      *
  112.      * @var HeaderBag
  113.      */
  114.     public $headers;
  115.     /**
  116.      * @var string|resource|false|null
  117.      */
  118.     protected $content;
  119.     /**
  120.      * @var string[]|null
  121.      */
  122.     protected $languages;
  123.     /**
  124.      * @var string[]|null
  125.      */
  126.     protected $charsets;
  127.     /**
  128.      * @var string[]|null
  129.      */
  130.     protected $encodings;
  131.     /**
  132.      * @var string[]|null
  133.      */
  134.     protected $acceptableContentTypes;
  135.     /**
  136.      * @var string|null
  137.      */
  138.     protected $pathInfo;
  139.     /**
  140.      * @var string|null
  141.      */
  142.     protected $requestUri;
  143.     /**
  144.      * @var string|null
  145.      */
  146.     protected $baseUrl;
  147.     /**
  148.      * @var string|null
  149.      */
  150.     protected $basePath;
  151.     /**
  152.      * @var string|null
  153.      */
  154.     protected $method;
  155.     /**
  156.      * @var string|null
  157.      */
  158.     protected $format;
  159.     /**
  160.      * @var SessionInterface|callable():SessionInterface|null
  161.      */
  162.     protected $session;
  163.     /**
  164.      * @var string|null
  165.      */
  166.     protected $locale;
  167.     /**
  168.      * @var string
  169.      */
  170.     protected $defaultLocale 'en';
  171.     /**
  172.      * @var array<string, string[]>|null
  173.      */
  174.     protected static $formats;
  175.     protected static $requestFactory;
  176.     private ?string $preferredFormat null;
  177.     private bool $isHostValid true;
  178.     private bool $isForwardedValid true;
  179.     private bool $isSafeContentPreferred;
  180.     private array $trustedValuesCache = [];
  181.     private static int $trustedHeaderSet = -1;
  182.     private const FORWARDED_PARAMS = [
  183.         self::HEADER_X_FORWARDED_FOR => 'for',
  184.         self::HEADER_X_FORWARDED_HOST => 'host',
  185.         self::HEADER_X_FORWARDED_PROTO => 'proto',
  186.         self::HEADER_X_FORWARDED_PORT => 'host',
  187.     ];
  188.     /**
  189.      * Names for headers that can be trusted when
  190.      * using trusted proxies.
  191.      *
  192.      * The FORWARDED header is the standard as of rfc7239.
  193.      *
  194.      * The other headers are non-standard, but widely used
  195.      * by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
  196.      */
  197.     private const TRUSTED_HEADERS = [
  198.         self::HEADER_FORWARDED => 'FORWARDED',
  199.         self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
  200.         self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
  201.         self::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
  202.         self::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
  203.         self::HEADER_X_FORWARDED_PREFIX => 'X_FORWARDED_PREFIX',
  204.     ];
  205.     /** @var bool */
  206.     private $isIisRewrite false;
  207.     /**
  208.      * @param array                $query      The GET parameters
  209.      * @param array                $request    The POST parameters
  210.      * @param array                $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  211.      * @param array                $cookies    The COOKIE parameters
  212.      * @param array                $files      The FILES parameters
  213.      * @param array                $server     The SERVER parameters
  214.      * @param string|resource|null $content    The raw body data
  215.      */
  216.     public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content null)
  217.     {
  218.         $this->initialize($query$request$attributes$cookies$files$server$content);
  219.     }
  220.     /**
  221.      * Sets the parameters for this request.
  222.      *
  223.      * This method also re-initializes all properties.
  224.      *
  225.      * @param array                $query      The GET parameters
  226.      * @param array                $request    The POST parameters
  227.      * @param array                $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  228.      * @param array                $cookies    The COOKIE parameters
  229.      * @param array                $files      The FILES parameters
  230.      * @param array                $server     The SERVER parameters
  231.      * @param string|resource|null $content    The raw body data
  232.      *
  233.      * @return void
  234.      */
  235.     public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content null)
  236.     {
  237.         $this->request = new InputBag($request);
  238.         $this->query = new InputBag($query);
  239.         $this->attributes = new ParameterBag($attributes);
  240.         $this->cookies = new InputBag($cookies);
  241.         $this->files = new FileBag($files);
  242.         $this->server = new ServerBag($server);
  243.         $this->headers = new HeaderBag($this->server->getHeaders());
  244.         $this->content $content;
  245.         $this->languages null;
  246.         $this->charsets null;
  247.         $this->encodings null;
  248.         $this->acceptableContentTypes null;
  249.         $this->pathInfo null;
  250.         $this->requestUri null;
  251.         $this->baseUrl null;
  252.         $this->basePath null;
  253.         $this->method null;
  254.         $this->format null;
  255.     }
  256.     /**
  257.      * Creates a new request with values from PHP's super globals.
  258.      */
  259.     public static function createFromGlobals(): static
  260.     {
  261.         $request self::createRequestFromFactory($_GET$_POST, [], $_COOKIE$_FILES$_SERVER);
  262.         if (str_starts_with($request->headers->get('CONTENT_TYPE'''), 'application/x-www-form-urlencoded')
  263.             && \in_array(strtoupper($request->server->get('REQUEST_METHOD''GET')), ['PUT''DELETE''PATCH'])
  264.         ) {
  265.             parse_str($request->getContent(), $data);
  266.             $request->request = new InputBag($data);
  267.         }
  268.         return $request;
  269.     }
  270.     /**
  271.      * Creates a Request based on a given URI and configuration.
  272.      *
  273.      * The information contained in the URI always take precedence
  274.      * over the other information (server and parameters).
  275.      *
  276.      * @param string               $uri        The URI
  277.      * @param string               $method     The HTTP method
  278.      * @param array                $parameters The query (GET) or request (POST) parameters
  279.      * @param array                $cookies    The request cookies ($_COOKIE)
  280.      * @param array                $files      The request files ($_FILES)
  281.      * @param array                $server     The server parameters ($_SERVER)
  282.      * @param string|resource|null $content    The raw body data
  283.      *
  284.      * @throws BadRequestException When the URI is invalid
  285.      */
  286.     public static function create(string $uristring $method 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content null): static
  287.     {
  288.         $server array_replace([
  289.             'SERVER_NAME' => 'localhost',
  290.             'SERVER_PORT' => 80,
  291.             'HTTP_HOST' => 'localhost',
  292.             'HTTP_USER_AGENT' => 'Symfony',
  293.             'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  294.             'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
  295.             'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  296.             'REMOTE_ADDR' => '127.0.0.1',
  297.             'SCRIPT_NAME' => '',
  298.             'SCRIPT_FILENAME' => '',
  299.             'SERVER_PROTOCOL' => 'HTTP/1.1',
  300.             'REQUEST_TIME' => time(),
  301.             'REQUEST_TIME_FLOAT' => microtime(true),
  302.         ], $server);
  303.         $server['PATH_INFO'] = '';
  304.         $server['REQUEST_METHOD'] = strtoupper($method);
  305.         if (($i strcspn($uri':/?#')) && ':' === ($uri[$i] ?? null) && (strspn($uri'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.') !== $i || strcspn($uri'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'))) {
  306.             throw new BadRequestException('Invalid URI: Scheme is malformed.');
  307.         }
  308.         if (false === $components parse_url(\strlen($uri) !== strcspn($uri'?#') ? $uri $uri.'#')) {
  309.             throw new BadRequestException('Invalid URI.');
  310.         }
  311.         $part = ($components['user'] ?? '').':'.($components['pass'] ?? '');
  312.         if (':' !== $part && \strlen($part) !== strcspn($part'[]')) {
  313.             throw new BadRequestException('Invalid URI: Userinfo is malformed.');
  314.         }
  315.         if (($part $components['host'] ?? '') && !self::isHostValid($part)) {
  316.             throw new BadRequestException('Invalid URI: Host is malformed.');
  317.         }
  318.         if (false !== ($i strpos($uri'\\')) && $i strcspn($uri'?#')) {
  319.             throw new BadRequestException('Invalid URI: A URI cannot contain a backslash.');
  320.         }
  321.         if (\strlen($uri) !== strcspn($uri"\r\n\t")) {
  322.             throw new BadRequestException('Invalid URI: A URI cannot contain CR/LF/TAB characters.');
  323.         }
  324.         if ('' !== $uri && (\ord($uri[0]) <= 32 || \ord($uri[-1]) <= 32)) {
  325.             throw new BadRequestException('Invalid URI: A URI must not start nor end with ASCII control characters or spaces.');
  326.         }
  327.         if (isset($components['host'])) {
  328.             $server['SERVER_NAME'] = $components['host'];
  329.             $server['HTTP_HOST'] = $components['host'];
  330.         }
  331.         if (isset($components['scheme'])) {
  332.             if ('https' === $components['scheme']) {
  333.                 $server['HTTPS'] = 'on';
  334.                 $server['SERVER_PORT'] = 443;
  335.             } else {
  336.                 unset($server['HTTPS']);
  337.                 $server['SERVER_PORT'] = 80;
  338.             }
  339.         }
  340.         if (isset($components['port'])) {
  341.             $server['SERVER_PORT'] = $components['port'];
  342.             $server['HTTP_HOST'] .= ':'.$components['port'];
  343.         }
  344.         if (isset($components['user'])) {
  345.             $server['PHP_AUTH_USER'] = $components['user'];
  346.         }
  347.         if (isset($components['pass'])) {
  348.             $server['PHP_AUTH_PW'] = $components['pass'];
  349.         }
  350.         if ('' === $path $components['path'] ?? '') {
  351.             $components['path'] = '/';
  352.         } elseif (!isset($components['scheme']) && !isset($components['host']) && '/' !== $path[0]) {
  353.             if (false !== $pos strpos($path'/')) {
  354.                 $path substr($path0$pos);
  355.             }
  356.             if (str_contains($path':')) {
  357.                 throw new BadRequestException('Invalid URI: Path is malformed.');
  358.             }
  359.         }
  360.         switch (strtoupper($method)) {
  361.             case 'POST':
  362.             case 'PUT':
  363.             case 'DELETE':
  364.                 if (!isset($server['CONTENT_TYPE'])) {
  365.                     $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  366.                 }
  367.                 // no break
  368.             case 'PATCH':
  369.                 $request $parameters;
  370.                 $query = [];
  371.                 break;
  372.             default:
  373.                 $request = [];
  374.                 $query $parameters;
  375.                 break;
  376.         }
  377.         $queryString '';
  378.         if (isset($components['query'])) {
  379.             parse_str(html_entity_decode($components['query']), $qs);
  380.             if ($query) {
  381.                 $query array_replace($qs$query);
  382.                 $queryString http_build_query($query'''&');
  383.             } else {
  384.                 $query $qs;
  385.                 $queryString $components['query'];
  386.             }
  387.         } elseif ($query) {
  388.             $queryString http_build_query($query'''&');
  389.         }
  390.         $server['REQUEST_URI'] = $components['path'].('' !== $queryString '?'.$queryString '');
  391.         $server['QUERY_STRING'] = $queryString;
  392.         return self::createRequestFromFactory($query$request, [], $cookies$files$server$content);
  393.     }
  394.     /**
  395.      * Sets a callable able to create a Request instance.
  396.      *
  397.      * This is mainly useful when you need to override the Request class
  398.      * to keep BC with an existing system. It should not be used for any
  399.      * other purpose.
  400.      *
  401.      * @return void
  402.      */
  403.     public static function setFactory(?callable $callable)
  404.     {
  405.         self::$requestFactory $callable;
  406.     }
  407.     /**
  408.      * Clones a request and overrides some of its parameters.
  409.      *
  410.      * @param array|null $query      The GET parameters
  411.      * @param array|null $request    The POST parameters
  412.      * @param array|null $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  413.      * @param array|null $cookies    The COOKIE parameters
  414.      * @param array|null $files      The FILES parameters
  415.      * @param array|null $server     The SERVER parameters
  416.      */
  417.     public function duplicate(?array $query null, ?array $request null, ?array $attributes null, ?array $cookies null, ?array $files null, ?array $server null): static
  418.     {
  419.         $dup = clone $this;
  420.         if (null !== $query) {
  421.             $dup->query = new InputBag($query);
  422.         }
  423.         if (null !== $request) {
  424.             $dup->request = new InputBag($request);
  425.         }
  426.         if (null !== $attributes) {
  427.             $dup->attributes = new ParameterBag($attributes);
  428.         }
  429.         if (null !== $cookies) {
  430.             $dup->cookies = new InputBag($cookies);
  431.         }
  432.         if (null !== $files) {
  433.             $dup->files = new FileBag($files);
  434.         }
  435.         if (null !== $server) {
  436.             $dup->server = new ServerBag($server);
  437.             $dup->headers = new HeaderBag($dup->server->getHeaders());
  438.         }
  439.         $dup->languages null;
  440.         $dup->charsets null;
  441.         $dup->encodings null;
  442.         $dup->acceptableContentTypes null;
  443.         $dup->pathInfo null;
  444.         $dup->requestUri null;
  445.         $dup->baseUrl null;
  446.         $dup->basePath null;
  447.         $dup->method null;
  448.         $dup->format null;
  449.         if (!$dup->get('_format') && $this->get('_format')) {
  450.             $dup->attributes->set('_format'$this->get('_format'));
  451.         }
  452.         if (!$dup->getRequestFormat(null)) {
  453.             $dup->setRequestFormat($this->getRequestFormat(null));
  454.         }
  455.         return $dup;
  456.     }
  457.     /**
  458.      * Clones the current request.
  459.      *
  460.      * Note that the session is not cloned as duplicated requests
  461.      * are most of the time sub-requests of the main one.
  462.      */
  463.     public function __clone()
  464.     {
  465.         $this->query = clone $this->query;
  466.         $this->request = clone $this->request;
  467.         $this->attributes = clone $this->attributes;
  468.         $this->cookies = clone $this->cookies;
  469.         $this->files = clone $this->files;
  470.         $this->server = clone $this->server;
  471.         $this->headers = clone $this->headers;
  472.     }
  473.     public function __toString(): string
  474.     {
  475.         $content $this->getContent();
  476.         $cookieHeader '';
  477.         $cookies = [];
  478.         foreach ($this->cookies as $k => $v) {
  479.             $cookies[] = \is_array($v) ? http_build_query([$k => $v], '''; '\PHP_QUERY_RFC3986) : "$k=$v";
  480.         }
  481.         if ($cookies) {
  482.             $cookieHeader 'Cookie: '.implode('; '$cookies)."\r\n";
  483.         }
  484.         return
  485.             \sprintf('%s %s %s'$this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
  486.             $this->headers.
  487.             $cookieHeader."\r\n".
  488.             $content;
  489.     }
  490.     /**
  491.      * Overrides the PHP global variables according to this request instance.
  492.      *
  493.      * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
  494.      * $_FILES is never overridden, see rfc1867
  495.      *
  496.      * @return void
  497.      */
  498.     public function overrideGlobals()
  499.     {
  500.         $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '''&')));
  501.         $_GET $this->query->all();
  502.         $_POST $this->request->all();
  503.         $_SERVER $this->server->all();
  504.         $_COOKIE $this->cookies->all();
  505.         foreach ($this->headers->all() as $key => $value) {
  506.             $key strtoupper(str_replace('-''_'$key));
  507.             if (\in_array($key, ['CONTENT_TYPE''CONTENT_LENGTH''CONTENT_MD5'], true)) {
  508.                 $_SERVER[$key] = implode(', '$value);
  509.             } else {
  510.                 $_SERVER['HTTP_'.$key] = implode(', '$value);
  511.             }
  512.         }
  513.         $request = ['g' => $_GET'p' => $_POST'c' => $_COOKIE];
  514.         $requestOrder \ini_get('request_order') ?: \ini_get('variables_order');
  515.         $requestOrder preg_replace('#[^cgp]#'''strtolower($requestOrder)) ?: 'gp';
  516.         $_REQUEST = [[]];
  517.         foreach (str_split($requestOrder) as $order) {
  518.             $_REQUEST[] = $request[$order];
  519.         }
  520.         $_REQUEST array_merge(...$_REQUEST);
  521.     }
  522.     /**
  523.      * Sets a list of trusted proxies.
  524.      *
  525.      * You should only list the reverse proxies that you manage directly.
  526.      *
  527.      * @param array $proxies          A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR']
  528.      * @param int   $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies
  529.      *
  530.      * @return void
  531.      */
  532.     public static function setTrustedProxies(array $proxiesint $trustedHeaderSet)
  533.     {
  534.         self::$trustedProxies array_reduce($proxies, function ($proxies$proxy) {
  535.             if ('REMOTE_ADDR' !== $proxy) {
  536.                 $proxies[] = $proxy;
  537.             } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  538.                 $proxies[] = $_SERVER['REMOTE_ADDR'];
  539.             }
  540.             return $proxies;
  541.         }, []);
  542.         self::$trustedHeaderSet $trustedHeaderSet;
  543.     }
  544.     /**
  545.      * Gets the list of trusted proxies.
  546.      *
  547.      * @return string[]
  548.      */
  549.     public static function getTrustedProxies(): array
  550.     {
  551.         return self::$trustedProxies;
  552.     }
  553.     /**
  554.      * Gets the set of trusted headers from trusted proxies.
  555.      *
  556.      * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies
  557.      */
  558.     public static function getTrustedHeaderSet(): int
  559.     {
  560.         return self::$trustedHeaderSet;
  561.     }
  562.     /**
  563.      * Sets a list of trusted host patterns.
  564.      *
  565.      * You should only list the hosts you manage using regexs.
  566.      *
  567.      * @param array $hostPatterns A list of trusted host patterns
  568.      *
  569.      * @return void
  570.      */
  571.     public static function setTrustedHosts(array $hostPatterns)
  572.     {
  573.         self::$trustedHostPatterns array_map(fn ($hostPattern) => \sprintf('{%s}i'$hostPattern), $hostPatterns);
  574.         // we need to reset trusted hosts on trusted host patterns change
  575.         self::$trustedHosts = [];
  576.     }
  577.     /**
  578.      * Gets the list of trusted host patterns.
  579.      *
  580.      * @return string[]
  581.      */
  582.     public static function getTrustedHosts(): array
  583.     {
  584.         return self::$trustedHostPatterns;
  585.     }
  586.     /**
  587.      * Normalizes a query string.
  588.      *
  589.      * It builds a normalized query string, where keys/value pairs are alphabetized,
  590.      * have consistent escaping and unneeded delimiters are removed.
  591.      */
  592.     public static function normalizeQueryString(?string $qs): string
  593.     {
  594.         if ('' === ($qs ?? '')) {
  595.             return '';
  596.         }
  597.         $qs HeaderUtils::parseQuery($qs);
  598.         ksort($qs);
  599.         return http_build_query($qs'''&'\PHP_QUERY_RFC3986);
  600.     }
  601.     /**
  602.      * Enables support for the _method request parameter to determine the intended HTTP method.
  603.      *
  604.      * Be warned that enabling this feature might lead to CSRF issues in your code.
  605.      * Check that you are using CSRF tokens when required.
  606.      * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
  607.      * and used to send a "PUT" or "DELETE" request via the _method request parameter.
  608.      * If these methods are not protected against CSRF, this presents a possible vulnerability.
  609.      *
  610.      * The HTTP method can only be overridden when the real HTTP method is POST.
  611.      *
  612.      * @return void
  613.      */
  614.     public static function enableHttpMethodParameterOverride()
  615.     {
  616.         self::$httpMethodParameterOverride true;
  617.     }
  618.     /**
  619.      * Checks whether support for the _method request parameter is enabled.
  620.      */
  621.     public static function getHttpMethodParameterOverride(): bool
  622.     {
  623.         return self::$httpMethodParameterOverride;
  624.     }
  625.     /**
  626.      * Gets a "parameter" value from any bag.
  627.      *
  628.      * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the
  629.      * flexibility in controllers, it is better to explicitly get request parameters from the appropriate
  630.      * public property instead (attributes, query, request).
  631.      *
  632.      * Order of precedence: PATH (routing placeholders or custom attributes), GET, POST
  633.      *
  634.      * @internal use explicit input sources instead
  635.      */
  636.     public function get(string $keymixed $default null): mixed
  637.     {
  638.         if ($this !== $result $this->attributes->get($key$this)) {
  639.             return $result;
  640.         }
  641.         if ($this->query->has($key)) {
  642.             return $this->query->all()[$key];
  643.         }
  644.         if ($this->request->has($key)) {
  645.             return $this->request->all()[$key];
  646.         }
  647.         return $default;
  648.     }
  649.     /**
  650.      * Gets the Session.
  651.      *
  652.      * @throws SessionNotFoundException When session is not set properly
  653.      */
  654.     public function getSession(): SessionInterface
  655.     {
  656.         $session $this->session;
  657.         if (!$session instanceof SessionInterface && null !== $session) {
  658.             $this->setSession($session $session());
  659.         }
  660.         if (null === $session) {
  661.             throw new SessionNotFoundException('Session has not been set.');
  662.         }
  663.         return $session;
  664.     }
  665.     /**
  666.      * Whether the request contains a Session which was started in one of the
  667.      * previous requests.
  668.      */
  669.     public function hasPreviousSession(): bool
  670.     {
  671.         // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
  672.         return $this->hasSession() && $this->cookies->has($this->getSession()->getName());
  673.     }
  674.     /**
  675.      * Whether the request contains a Session object.
  676.      *
  677.      * This method does not give any information about the state of the session object,
  678.      * like whether the session is started or not. It is just a way to check if this Request
  679.      * is associated with a Session instance.
  680.      *
  681.      * @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory`
  682.      */
  683.     public function hasSession(bool $skipIfUninitialized false): bool
  684.     {
  685.         return null !== $this->session && (!$skipIfUninitialized || $this->session instanceof SessionInterface);
  686.     }
  687.     /**
  688.      * @return void
  689.      */
  690.     public function setSession(SessionInterface $session)
  691.     {
  692.         $this->session $session;
  693.     }
  694.     /**
  695.      * @internal
  696.      *
  697.      * @param callable(): SessionInterface $factory
  698.      */
  699.     public function setSessionFactory(callable $factory): void
  700.     {
  701.         $this->session $factory(...);
  702.     }
  703.     /**
  704.      * Returns the client IP addresses.
  705.      *
  706.      * In the returned array the most trusted IP address is first, and the
  707.      * least trusted one last. The "real" client IP address is the last one,
  708.      * but this is also the least trusted one. Trusted proxies are stripped.
  709.      *
  710.      * Use this method carefully; you should use getClientIp() instead.
  711.      *
  712.      * @see getClientIp()
  713.      */
  714.     public function getClientIps(): array
  715.     {
  716.         $ip $this->server->get('REMOTE_ADDR');
  717.         if (!$this->isFromTrustedProxy()) {
  718.             return [$ip];
  719.         }
  720.         return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR$ip) ?: [$ip];
  721.     }
  722.     /**
  723.      * Returns the client IP address.
  724.      *
  725.      * This method can read the client IP address from the "X-Forwarded-For" header
  726.      * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
  727.      * header value is a comma+space separated list of IP addresses, the left-most
  728.      * being the original client, and each successive proxy that passed the request
  729.      * adding the IP address where it received the request from.
  730.      *
  731.      * If your reverse proxy uses a different header name than "X-Forwarded-For",
  732.      * ("Client-Ip" for instance), configure it via the $trustedHeaderSet
  733.      * argument of the Request::setTrustedProxies() method instead.
  734.      *
  735.      * @see getClientIps()
  736.      * @see https://wikipedia.org/wiki/X-Forwarded-For
  737.      */
  738.     public function getClientIp(): ?string
  739.     {
  740.         $ipAddresses $this->getClientIps();
  741.         return $ipAddresses[0];
  742.     }
  743.     /**
  744.      * Returns current script name.
  745.      */
  746.     public function getScriptName(): string
  747.     {
  748.         return $this->server->get('SCRIPT_NAME'$this->server->get('ORIG_SCRIPT_NAME'''));
  749.     }
  750.     /**
  751.      * Returns the path being requested relative to the executed script.
  752.      *
  753.      * The path info always starts with a /.
  754.      *
  755.      * Suppose this request is instantiated from /mysite on localhost:
  756.      *
  757.      *  * http://localhost/mysite              returns '/'
  758.      *  * http://localhost/mysite/about        returns '/about'
  759.      *  * http://localhost/mysite/enco%20ded   returns '/enco%20ded'
  760.      *  * http://localhost/mysite/about?var=1  returns '/about'
  761.      *
  762.      * @return string The raw path (i.e. not urldecoded)
  763.      */
  764.     public function getPathInfo(): string
  765.     {
  766.         return $this->pathInfo ??= $this->preparePathInfo();
  767.     }
  768.     /**
  769.      * Returns the root path from which this request is executed.
  770.      *
  771.      * Suppose that an index.php file instantiates this request object:
  772.      *
  773.      *  * http://localhost/index.php         returns an empty string
  774.      *  * http://localhost/index.php/page    returns an empty string
  775.      *  * http://localhost/web/index.php     returns '/web'
  776.      *  * http://localhost/we%20b/index.php  returns '/we%20b'
  777.      *
  778.      * @return string The raw path (i.e. not urldecoded)
  779.      */
  780.     public function getBasePath(): string
  781.     {
  782.         return $this->basePath ??= $this->prepareBasePath();
  783.     }
  784.     /**
  785.      * Returns the root URL from which this request is executed.
  786.      *
  787.      * The base URL never ends with a /.
  788.      *
  789.      * This is similar to getBasePath(), except that it also includes the
  790.      * script filename (e.g. index.php) if one exists.
  791.      *
  792.      * @return string The raw URL (i.e. not urldecoded)
  793.      */
  794.     public function getBaseUrl(): string
  795.     {
  796.         $trustedPrefix '';
  797.         // the proxy prefix must be prepended to any prefix being needed at the webserver level
  798.         if ($this->isFromTrustedProxy() && $trustedPrefixValues $this->getTrustedValues(self::HEADER_X_FORWARDED_PREFIX)) {
  799.             $trustedPrefix rtrim($trustedPrefixValues[0], '/');
  800.         }
  801.         return $trustedPrefix.$this->getBaseUrlReal();
  802.     }
  803.     /**
  804.      * Returns the real base URL received by the webserver from which this request is executed.
  805.      * The URL does not include trusted reverse proxy prefix.
  806.      *
  807.      * @return string The raw URL (i.e. not urldecoded)
  808.      */
  809.     private function getBaseUrlReal(): string
  810.     {
  811.         return $this->baseUrl ??= $this->prepareBaseUrl();
  812.     }
  813.     /**
  814.      * Gets the request's scheme.
  815.      */
  816.     public function getScheme(): string
  817.     {
  818.         return $this->isSecure() ? 'https' 'http';
  819.     }
  820.     /**
  821.      * Returns the port on which the request is made.
  822.      *
  823.      * This method can read the client port from the "X-Forwarded-Port" header
  824.      * when trusted proxies were set via "setTrustedProxies()".
  825.      *
  826.      * The "X-Forwarded-Port" header must contain the client port.
  827.      *
  828.      * @return int|string|null Can be a string if fetched from the server bag
  829.      */
  830.     public function getPort(): int|string|null
  831.     {
  832.         if ($this->isFromTrustedProxy() && $host $this->getTrustedValues(self::HEADER_X_FORWARDED_PORT)) {
  833.             $host $host[0];
  834.         } elseif ($this->isFromTrustedProxy() && $host $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
  835.             $host $host[0];
  836.         } elseif (!$host $this->headers->get('HOST')) {
  837.             return $this->server->get('SERVER_PORT');
  838.         }
  839.         if ('[' === $host[0]) {
  840.             $pos strpos($host':'strrpos($host']'));
  841.         } else {
  842.             $pos strrpos($host':');
  843.         }
  844.         if (false !== $pos && $port substr($host$pos 1)) {
  845.             return (int) $port;
  846.         }
  847.         return 'https' === $this->getScheme() ? 443 80;
  848.     }
  849.     /**
  850.      * Returns the user.
  851.      */
  852.     public function getUser(): ?string
  853.     {
  854.         return $this->headers->get('PHP_AUTH_USER');
  855.     }
  856.     /**
  857.      * Returns the password.
  858.      */
  859.     public function getPassword(): ?string
  860.     {
  861.         return $this->headers->get('PHP_AUTH_PW');
  862.     }
  863.     /**
  864.      * Gets the user info.
  865.      *
  866.      * @return string|null A user name if any and, optionally, scheme-specific information about how to gain authorization to access the server
  867.      */
  868.     public function getUserInfo(): ?string
  869.     {
  870.         $userinfo $this->getUser();
  871.         $pass $this->getPassword();
  872.         if ('' != $pass) {
  873.             $userinfo .= ":$pass";
  874.         }
  875.         return $userinfo;
  876.     }
  877.     /**
  878.      * Returns the HTTP host being requested.
  879.      *
  880.      * The port name will be appended to the host if it's non-standard.
  881.      */
  882.     public function getHttpHost(): string
  883.     {
  884.         $scheme $this->getScheme();
  885.         $port $this->getPort();
  886.         if (('http' === $scheme && 80 == $port) || ('https' === $scheme && 443 == $port)) {
  887.             return $this->getHost();
  888.         }
  889.         return $this->getHost().':'.$port;
  890.     }
  891.     /**
  892.      * Returns the requested URI (path and query string).
  893.      *
  894.      * @return string The raw URI (i.e. not URI decoded)
  895.      */
  896.     public function getRequestUri(): string
  897.     {
  898.         return $this->requestUri ??= $this->prepareRequestUri();
  899.     }
  900.     /**
  901.      * Gets the scheme and HTTP host.
  902.      *
  903.      * If the URL was called with basic authentication, the user
  904.      * and the password are not added to the generated string.
  905.      */
  906.     public function getSchemeAndHttpHost(): string
  907.     {
  908.         return $this->getScheme().'://'.$this->getHttpHost();
  909.     }
  910.     /**
  911.      * Generates a normalized URI (URL) for the Request.
  912.      *
  913.      * @see getQueryString()
  914.      */
  915.     public function getUri(): string
  916.     {
  917.         if (null !== $qs $this->getQueryString()) {
  918.             $qs '?'.$qs;
  919.         }
  920.         return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  921.     }
  922.     /**
  923.      * Generates a normalized URI for the given path.
  924.      *
  925.      * @param string $path A path to use instead of the current one
  926.      */
  927.     public function getUriForPath(string $path): string
  928.     {
  929.         return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
  930.     }
  931.     /**
  932.      * Returns the path as relative reference from the current Request path.
  933.      *
  934.      * Only the URIs path component (no schema, host etc.) is relevant and must be given.
  935.      * Both paths must be absolute and not contain relative parts.
  936.      * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
  937.      * Furthermore, they can be used to reduce the link size in documents.
  938.      *
  939.      * Example target paths, given a base path of "/a/b/c/d":
  940.      * - "/a/b/c/d"     -> ""
  941.      * - "/a/b/c/"      -> "./"
  942.      * - "/a/b/"        -> "../"
  943.      * - "/a/b/c/other" -> "other"
  944.      * - "/a/x/y"       -> "../../x/y"
  945.      */
  946.     public function getRelativeUriForPath(string $path): string
  947.     {
  948.         // be sure that we are dealing with an absolute path
  949.         if (!isset($path[0]) || '/' !== $path[0]) {
  950.             return $path;
  951.         }
  952.         if ($path === $basePath $this->getPathInfo()) {
  953.             return '';
  954.         }
  955.         $sourceDirs explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath1) : $basePath);
  956.         $targetDirs explode('/'substr($path1));
  957.         array_pop($sourceDirs);
  958.         $targetFile array_pop($targetDirs);
  959.         foreach ($sourceDirs as $i => $dir) {
  960.             if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  961.                 unset($sourceDirs[$i], $targetDirs[$i]);
  962.             } else {
  963.                 break;
  964.             }
  965.         }
  966.         $targetDirs[] = $targetFile;
  967.         $path str_repeat('../'\count($sourceDirs)).implode('/'$targetDirs);
  968.         // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  969.         // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  970.         // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  971.         // (see https://tools.ietf.org/html/rfc3986#section-4.2).
  972.         return !isset($path[0]) || '/' === $path[0]
  973.             || false !== ($colonPos strpos($path':')) && ($colonPos < ($slashPos strpos($path'/')) || false === $slashPos)
  974.             ? "./$path$path;
  975.     }
  976.     /**
  977.      * Generates the normalized query string for the Request.
  978.      *
  979.      * It builds a normalized query string, where keys/value pairs are alphabetized
  980.      * and have consistent escaping.
  981.      */
  982.     public function getQueryString(): ?string
  983.     {
  984.         $qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
  985.         return '' === $qs null $qs;
  986.     }
  987.     /**
  988.      * Checks whether the request is secure or not.
  989.      *
  990.      * This method can read the client protocol from the "X-Forwarded-Proto" header
  991.      * when trusted proxies were set via "setTrustedProxies()".
  992.      *
  993.      * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
  994.      */
  995.     public function isSecure(): bool
  996.     {
  997.         if ($this->isFromTrustedProxy() && $proto $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) {
  998.             return \in_array(strtolower($proto[0]), ['https''on''ssl''1'], true);
  999.         }
  1000.         $https $this->server->get('HTTPS');
  1001.         return !empty($https) && 'off' !== strtolower($https);
  1002.     }
  1003.     /**
  1004.      * Returns the host name.
  1005.      *
  1006.      * This method can read the client host name from the "X-Forwarded-Host" header
  1007.      * when trusted proxies were set via "setTrustedProxies()".
  1008.      *
  1009.      * The "X-Forwarded-Host" header must contain the client host name.
  1010.      *
  1011.      * @throws SuspiciousOperationException when the host name is invalid or not trusted
  1012.      */
  1013.     public function getHost(): string
  1014.     {
  1015.         if ($this->isFromTrustedProxy() && $host $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
  1016.             $host $host[0];
  1017.         } elseif (!$host $this->headers->get('HOST')) {
  1018.             if (!$host $this->server->get('SERVER_NAME')) {
  1019.                 $host $this->server->get('SERVER_ADDR''');
  1020.             }
  1021.         }
  1022.         // trim and remove port number from host
  1023.         // host is lowercase as per RFC 952/2181
  1024.         $host strtolower(preg_replace('/:\d+$/'''trim($host)));
  1025.         // the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
  1026.         if ($host && !self::isHostValid($host)) {
  1027.             if (!$this->isHostValid) {
  1028.                 return '';
  1029.             }
  1030.             $this->isHostValid false;
  1031.             throw new SuspiciousOperationException(\sprintf('Invalid Host "%s".'$host));
  1032.         }
  1033.         if (\count(self::$trustedHostPatterns) > 0) {
  1034.             // to avoid host header injection attacks, you should provide a list of trusted host patterns
  1035.             if (\in_array($hostself::$trustedHosts)) {
  1036.                 return $host;
  1037.             }
  1038.             foreach (self::$trustedHostPatterns as $pattern) {
  1039.                 if (preg_match($pattern$host)) {
  1040.                     self::$trustedHosts[] = $host;
  1041.                     return $host;
  1042.                 }
  1043.             }
  1044.             if (!$this->isHostValid) {
  1045.                 return '';
  1046.             }
  1047.             $this->isHostValid false;
  1048.             throw new SuspiciousOperationException(\sprintf('Untrusted Host "%s".'$host));
  1049.         }
  1050.         return $host;
  1051.     }
  1052.     /**
  1053.      * Sets the request method.
  1054.      *
  1055.      * @return void
  1056.      */
  1057.     public function setMethod(string $method)
  1058.     {
  1059.         $this->method null;
  1060.         $this->server->set('REQUEST_METHOD'$method);
  1061.     }
  1062.     /**
  1063.      * Gets the request "intended" method.
  1064.      *
  1065.      * If the X-HTTP-Method-Override header is set, and if the method is a POST,
  1066.      * then it is used to determine the "real" intended HTTP method.
  1067.      *
  1068.      * The _method request parameter can also be used to determine the HTTP method,
  1069.      * but only if enableHttpMethodParameterOverride() has been called.
  1070.      *
  1071.      * The method is always an uppercased string.
  1072.      *
  1073.      * @see getRealMethod()
  1074.      */
  1075.     public function getMethod(): string
  1076.     {
  1077.         if (null !== $this->method) {
  1078.             return $this->method;
  1079.         }
  1080.         $this->method strtoupper($this->server->get('REQUEST_METHOD''GET'));
  1081.         if ('POST' !== $this->method) {
  1082.             return $this->method;
  1083.         }
  1084.         $method $this->headers->get('X-HTTP-METHOD-OVERRIDE');
  1085.         if (!$method && self::$httpMethodParameterOverride) {
  1086.             $method $this->request->get('_method'$this->query->get('_method''POST'));
  1087.         }
  1088.         if (!\is_string($method)) {
  1089.             return $this->method;
  1090.         }
  1091.         $method strtoupper($method);
  1092.         if (\in_array($method, ['GET''HEAD''POST''PUT''DELETE''CONNECT''OPTIONS''PATCH''PURGE''TRACE'], true)) {
  1093.             return $this->method $method;
  1094.         }
  1095.         if (!preg_match('/^[A-Z]++$/D'$method)) {
  1096.             throw new SuspiciousOperationException('Invalid HTTP method override.');
  1097.         }
  1098.         return $this->method $method;
  1099.     }
  1100.     /**
  1101.      * Gets the "real" request method.
  1102.      *
  1103.      * @see getMethod()
  1104.      */
  1105.     public function getRealMethod(): string
  1106.     {
  1107.         return strtoupper($this->server->get('REQUEST_METHOD''GET'));
  1108.     }
  1109.     /**
  1110.      * Gets the mime type associated with the format.
  1111.      */
  1112.     public function getMimeType(string $format): ?string
  1113.     {
  1114.         if (null === static::$formats) {
  1115.             static::initializeFormats();
  1116.         }
  1117.         return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  1118.     }
  1119.     /**
  1120.      * Gets the mime types associated with the format.
  1121.      *
  1122.      * @return string[]
  1123.      */
  1124.     public static function getMimeTypes(string $format): array
  1125.     {
  1126.         if (null === static::$formats) {
  1127.             static::initializeFormats();
  1128.         }
  1129.         return static::$formats[$format] ?? [];
  1130.     }
  1131.     /**
  1132.      * Gets the format associated with the mime type.
  1133.      */
  1134.     public function getFormat(?string $mimeType): ?string
  1135.     {
  1136.         $canonicalMimeType null;
  1137.         if ($mimeType && false !== $pos strpos($mimeType';')) {
  1138.             $canonicalMimeType trim(substr($mimeType0$pos));
  1139.         }
  1140.         if (null === static::$formats) {
  1141.             static::initializeFormats();
  1142.         }
  1143.         $exactFormat null;
  1144.         $canonicalFormat null;
  1145.         foreach (static::$formats as $format => $mimeTypes) {
  1146.             if (\in_array($mimeType$mimeTypestrue)) {
  1147.                 $exactFormat $format;
  1148.             }
  1149.             if (null !== $canonicalMimeType && \in_array($canonicalMimeType$mimeTypestrue)) {
  1150.                 $canonicalFormat $format;
  1151.             }
  1152.         }
  1153.         if ($format $exactFormat ?? $canonicalFormat) {
  1154.             return $format;
  1155.         }
  1156.         return null;
  1157.     }
  1158.     /**
  1159.      * Associates a format with mime types.
  1160.      *
  1161.      * @param string|string[] $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  1162.      *
  1163.      * @return void
  1164.      */
  1165.     public function setFormat(?string $formatstring|array $mimeTypes)
  1166.     {
  1167.         if (null === static::$formats) {
  1168.             static::initializeFormats();
  1169.         }
  1170.         static::$formats[$format ?? ''] = (array) $mimeTypes;
  1171.     }
  1172.     /**
  1173.      * Gets the request format.
  1174.      *
  1175.      * Here is the process to determine the format:
  1176.      *
  1177.      *  * format defined by the user (with setRequestFormat())
  1178.      *  * _format request attribute
  1179.      *  * $default
  1180.      *
  1181.      * @see getPreferredFormat
  1182.      */
  1183.     public function getRequestFormat(?string $default 'html'): ?string
  1184.     {
  1185.         $this->format ??= $this->attributes->get('_format');
  1186.         return $this->format ?? $default;
  1187.     }
  1188.     /**
  1189.      * Sets the request format.
  1190.      *
  1191.      * @return void
  1192.      */
  1193.     public function setRequestFormat(?string $format)
  1194.     {
  1195.         $this->format $format;
  1196.     }
  1197.     /**
  1198.      * Gets the usual name of the format associated with the request's media type (provided in the Content-Type header).
  1199.      *
  1200.      * @deprecated since Symfony 6.2, use getContentTypeFormat() instead
  1201.      */
  1202.     public function getContentType(): ?string
  1203.     {
  1204.         trigger_deprecation('symfony/http-foundation''6.2''The "%s()" method is deprecated, use "getContentTypeFormat()" instead.'__METHOD__);
  1205.         return $this->getContentTypeFormat();
  1206.     }
  1207.     /**
  1208.      * Gets the usual name of the format associated with the request's media type (provided in the Content-Type header).
  1209.      *
  1210.      * @see Request::$formats
  1211.      */
  1212.     public function getContentTypeFormat(): ?string
  1213.     {
  1214.         return $this->getFormat($this->headers->get('CONTENT_TYPE'''));
  1215.     }
  1216.     /**
  1217.      * Sets the default locale.
  1218.      *
  1219.      * @return void
  1220.      */
  1221.     public function setDefaultLocale(string $locale)
  1222.     {
  1223.         $this->defaultLocale $locale;
  1224.         if (null === $this->locale) {
  1225.             $this->setPhpDefaultLocale($locale);
  1226.         }
  1227.     }
  1228.     /**
  1229.      * Get the default locale.
  1230.      */
  1231.     public function getDefaultLocale(): string
  1232.     {
  1233.         return $this->defaultLocale;
  1234.     }
  1235.     /**
  1236.      * Sets the locale.
  1237.      *
  1238.      * @return void
  1239.      */
  1240.     public function setLocale(string $locale)
  1241.     {
  1242.         $this->setPhpDefaultLocale($this->locale $locale);
  1243.     }
  1244.     /**
  1245.      * Get the locale.
  1246.      */
  1247.     public function getLocale(): string
  1248.     {
  1249.         return $this->locale ?? $this->defaultLocale;
  1250.     }
  1251.     /**
  1252.      * Checks if the request method is of specified type.
  1253.      *
  1254.      * @param string $method Uppercase request method (GET, POST etc)
  1255.      */
  1256.     public function isMethod(string $method): bool
  1257.     {
  1258.         return $this->getMethod() === strtoupper($method);
  1259.     }
  1260.     /**
  1261.      * Checks whether or not the method is safe.
  1262.      *
  1263.      * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
  1264.      */
  1265.     public function isMethodSafe(): bool
  1266.     {
  1267.         return \in_array($this->getMethod(), ['GET''HEAD''OPTIONS''TRACE']);
  1268.     }
  1269.     /**
  1270.      * Checks whether or not the method is idempotent.
  1271.      */
  1272.     public function isMethodIdempotent(): bool
  1273.     {
  1274.         return \in_array($this->getMethod(), ['HEAD''GET''PUT''DELETE''TRACE''OPTIONS''PURGE']);
  1275.     }
  1276.     /**
  1277.      * Checks whether the method is cacheable or not.
  1278.      *
  1279.      * @see https://tools.ietf.org/html/rfc7231#section-4.2.3
  1280.      */
  1281.     public function isMethodCacheable(): bool
  1282.     {
  1283.         return \in_array($this->getMethod(), ['GET''HEAD']);
  1284.     }
  1285.     /**
  1286.      * Returns the protocol version.
  1287.      *
  1288.      * If the application is behind a proxy, the protocol version used in the
  1289.      * requests between the client and the proxy and between the proxy and the
  1290.      * server might be different. This returns the former (from the "Via" header)
  1291.      * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns
  1292.      * the latter (from the "SERVER_PROTOCOL" server parameter).
  1293.      */
  1294.     public function getProtocolVersion(): ?string
  1295.     {
  1296.         if ($this->isFromTrustedProxy()) {
  1297.             preg_match('~^(HTTP/)?([1-9]\.[0-9])\b~'$this->headers->get('Via') ?? ''$matches);
  1298.             if ($matches) {
  1299.                 return 'HTTP/'.$matches[2];
  1300.             }
  1301.         }
  1302.         return $this->server->get('SERVER_PROTOCOL');
  1303.     }
  1304.     /**
  1305.      * Returns the request body content.
  1306.      *
  1307.      * @param bool $asResource If true, a resource will be returned
  1308.      *
  1309.      * @return string|resource
  1310.      *
  1311.      * @psalm-return ($asResource is true ? resource : string)
  1312.      */
  1313.     public function getContent(bool $asResource false)
  1314.     {
  1315.         $currentContentIsResource \is_resource($this->content);
  1316.         if (true === $asResource) {
  1317.             if ($currentContentIsResource) {
  1318.                 rewind($this->content);
  1319.                 return $this->content;
  1320.             }
  1321.             // Content passed in parameter (test)
  1322.             if (\is_string($this->content)) {
  1323.                 $resource fopen('php://temp''r+');
  1324.                 fwrite($resource$this->content);
  1325.                 rewind($resource);
  1326.                 return $resource;
  1327.             }
  1328.             $this->content false;
  1329.             return fopen('php://input''r');
  1330.         }
  1331.         if ($currentContentIsResource) {
  1332.             rewind($this->content);
  1333.             return stream_get_contents($this->content);
  1334.         }
  1335.         if (null === $this->content || false === $this->content) {
  1336.             $this->content file_get_contents('php://input');
  1337.         }
  1338.         return $this->content;
  1339.     }
  1340.     /**
  1341.      * Gets the decoded form or json request body.
  1342.      *
  1343.      * @throws JsonException When the body cannot be decoded to an array
  1344.      */
  1345.     public function getPayload(): InputBag
  1346.     {
  1347.         if ($this->request->count()) {
  1348.             return clone $this->request;
  1349.         }
  1350.         if ('' === $content $this->getContent()) {
  1351.             return new InputBag([]);
  1352.         }
  1353.         try {
  1354.             $content json_decode($contenttrue512\JSON_BIGINT_AS_STRING \JSON_THROW_ON_ERROR);
  1355.         } catch (\JsonException $e) {
  1356.             throw new JsonException('Could not decode request body.'$e->getCode(), $e);
  1357.         }
  1358.         if (!\is_array($content)) {
  1359.             throw new JsonException(\sprintf('JSON content was expected to decode to an array, "%s" returned.'get_debug_type($content)));
  1360.         }
  1361.         return new InputBag($content);
  1362.     }
  1363.     /**
  1364.      * Gets the request body decoded as array, typically from a JSON payload.
  1365.      *
  1366.      * @see getPayload() for portability between content types
  1367.      *
  1368.      * @throws JsonException When the body cannot be decoded to an array
  1369.      */
  1370.     public function toArray(): array
  1371.     {
  1372.         if ('' === $content $this->getContent()) {
  1373.             throw new JsonException('Request body is empty.');
  1374.         }
  1375.         try {
  1376.             $content json_decode($contenttrue512\JSON_BIGINT_AS_STRING \JSON_THROW_ON_ERROR);
  1377.         } catch (\JsonException $e) {
  1378.             throw new JsonException('Could not decode request body.'$e->getCode(), $e);
  1379.         }
  1380.         if (!\is_array($content)) {
  1381.             throw new JsonException(\sprintf('JSON content was expected to decode to an array, "%s" returned.'get_debug_type($content)));
  1382.         }
  1383.         return $content;
  1384.     }
  1385.     /**
  1386.      * Gets the Etags.
  1387.      */
  1388.     public function getETags(): array
  1389.     {
  1390.         return preg_split('/\s*,\s*/'$this->headers->get('If-None-Match'''), -1\PREG_SPLIT_NO_EMPTY);
  1391.     }
  1392.     public function isNoCache(): bool
  1393.     {
  1394.         return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  1395.     }
  1396.     /**
  1397.      * Gets the preferred format for the response by inspecting, in the following order:
  1398.      *   * the request format set using setRequestFormat;
  1399.      *   * the values of the Accept HTTP header.
  1400.      *
  1401.      * Note that if you use this method, you should send the "Vary: Accept" header
  1402.      * in the response to prevent any issues with intermediary HTTP caches.
  1403.      */
  1404.     public function getPreferredFormat(?string $default 'html'): ?string
  1405.     {
  1406.         if ($this->preferredFormat ??= $this->getRequestFormat(null)) {
  1407.             return $this->preferredFormat;
  1408.         }
  1409.         foreach ($this->getAcceptableContentTypes() as $mimeType) {
  1410.             if ($this->preferredFormat $this->getFormat($mimeType)) {
  1411.                 return $this->preferredFormat;
  1412.             }
  1413.         }
  1414.         return $default;
  1415.     }
  1416.     /**
  1417.      * Returns the preferred language.
  1418.      *
  1419.      * @param string[] $locales An array of ordered available locales
  1420.      */
  1421.     public function getPreferredLanguage(?array $locales null): ?string
  1422.     {
  1423.         $preferredLanguages $this->getLanguages();
  1424.         if (empty($locales)) {
  1425.             return $preferredLanguages[0] ?? null;
  1426.         }
  1427.         if (!$preferredLanguages) {
  1428.             return $locales[0];
  1429.         }
  1430.         $extendedPreferredLanguages = [];
  1431.         foreach ($preferredLanguages as $language) {
  1432.             $extendedPreferredLanguages[] = $language;
  1433.             if (false !== $position strpos($language'_')) {
  1434.                 $superLanguage substr($language0$position);
  1435.                 if (!\in_array($superLanguage$preferredLanguages)) {
  1436.                     $extendedPreferredLanguages[] = $superLanguage;
  1437.                 }
  1438.             }
  1439.         }
  1440.         $preferredLanguages array_values(array_intersect($extendedPreferredLanguages$locales));
  1441.         return $preferredLanguages[0] ?? $locales[0];
  1442.     }
  1443.     /**
  1444.      * Gets a list of languages acceptable by the client browser ordered in the user browser preferences.
  1445.      *
  1446.      * @return string[]
  1447.      */
  1448.     public function getLanguages(): array
  1449.     {
  1450.         if (null !== $this->languages) {
  1451.             return $this->languages;
  1452.         }
  1453.         $languages AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
  1454.         $this->languages = [];
  1455.         foreach ($languages as $acceptHeaderItem) {
  1456.             $lang $acceptHeaderItem->getValue();
  1457.             if (str_contains($lang'-')) {
  1458.                 $codes explode('-'$lang);
  1459.                 if ('i' === $codes[0]) {
  1460.                     // Language not listed in ISO 639 that are not variants
  1461.                     // of any listed language, which can be registered with the
  1462.                     // i-prefix, such as i-cherokee
  1463.                     if (\count($codes) > 1) {
  1464.                         $lang $codes[1];
  1465.                     }
  1466.                 } else {
  1467.                     for ($i 0$max \count($codes); $i $max; ++$i) {
  1468.                         if (=== $i) {
  1469.                             $lang strtolower($codes[0]);
  1470.                         } else {
  1471.                             $lang .= '_'.strtoupper($codes[$i]);
  1472.                         }
  1473.                     }
  1474.                 }
  1475.             }
  1476.             $this->languages[] = $lang;
  1477.         }
  1478.         return $this->languages;
  1479.     }
  1480.     /**
  1481.      * Gets a list of charsets acceptable by the client browser in preferable order.
  1482.      *
  1483.      * @return string[]
  1484.      */
  1485.     public function getCharsets(): array
  1486.     {
  1487.         return $this->charsets ??= array_map('strval'array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()));
  1488.     }
  1489.     /**
  1490.      * Gets a list of encodings acceptable by the client browser in preferable order.
  1491.      *
  1492.      * @return string[]
  1493.      */
  1494.     public function getEncodings(): array
  1495.     {
  1496.         return $this->encodings ??= array_map('strval'array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all()));
  1497.     }
  1498.     /**
  1499.      * Gets a list of content types acceptable by the client browser in preferable order.
  1500.      *
  1501.      * @return string[]
  1502.      */
  1503.     public function getAcceptableContentTypes(): array
  1504.     {
  1505.         return $this->acceptableContentTypes ??= array_map('strval'array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()));
  1506.     }
  1507.     /**
  1508.      * Returns true if the request is an XMLHttpRequest.
  1509.      *
  1510.      * It works if your JavaScript library sets an X-Requested-With HTTP header.
  1511.      * It is known to work with common JavaScript frameworks:
  1512.      *
  1513.      * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
  1514.      */
  1515.     public function isXmlHttpRequest(): bool
  1516.     {
  1517.         return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  1518.     }
  1519.     /**
  1520.      * Checks whether the client browser prefers safe content or not according to RFC8674.
  1521.      *
  1522.      * @see https://tools.ietf.org/html/rfc8674
  1523.      */
  1524.     public function preferSafeContent(): bool
  1525.     {
  1526.         if (isset($this->isSafeContentPreferred)) {
  1527.             return $this->isSafeContentPreferred;
  1528.         }
  1529.         if (!$this->isSecure()) {
  1530.             // see https://tools.ietf.org/html/rfc8674#section-3
  1531.             return $this->isSafeContentPreferred false;
  1532.         }
  1533.         return $this->isSafeContentPreferred AcceptHeader::fromString($this->headers->get('Prefer'))->has('safe');
  1534.     }
  1535.     /*
  1536.      * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  1537.      *
  1538.      * Code subject to the new BSD license (https://framework.zend.com/license).
  1539.      *
  1540.      * Copyright (c) 2005-2010 Zend Technologies USA Inc. (https://www.zend.com/)
  1541.      */
  1542.     /**
  1543.      * @return string
  1544.      */
  1545.     protected function prepareRequestUri()
  1546.     {
  1547.         $requestUri '';
  1548.         if ($this->isIisRewrite() && '' != $this->server->get('UNENCODED_URL')) {
  1549.             // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
  1550.             $requestUri $this->server->get('UNENCODED_URL');
  1551.             $this->server->remove('UNENCODED_URL');
  1552.         } elseif ($this->server->has('REQUEST_URI')) {
  1553.             $requestUri $this->server->get('REQUEST_URI');
  1554.             if ('' !== $requestUri && '/' === $requestUri[0]) {
  1555.                 // To only use path and query remove the fragment.
  1556.                 if (false !== $pos strpos($requestUri'#')) {
  1557.                     $requestUri substr($requestUri0$pos);
  1558.                 }
  1559.             } else {
  1560.                 // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path,
  1561.                 // only use URL path.
  1562.                 $uriComponents parse_url($requestUri);
  1563.                 if (isset($uriComponents['path'])) {
  1564.                     $requestUri $uriComponents['path'];
  1565.                 }
  1566.                 if (isset($uriComponents['query'])) {
  1567.                     $requestUri .= '?'.$uriComponents['query'];
  1568.                 }
  1569.             }
  1570.         } elseif ($this->server->has('ORIG_PATH_INFO')) {
  1571.             // IIS 5.0, PHP as CGI
  1572.             $requestUri $this->server->get('ORIG_PATH_INFO');
  1573.             if ('' != $this->server->get('QUERY_STRING')) {
  1574.                 $requestUri .= '?'.$this->server->get('QUERY_STRING');
  1575.             }
  1576.             $this->server->remove('ORIG_PATH_INFO');
  1577.         }
  1578.         // normalize the request URI to ease creating sub-requests from this request
  1579.         $this->server->set('REQUEST_URI'$requestUri);
  1580.         return $requestUri;
  1581.     }
  1582.     /**
  1583.      * Prepares the base URL.
  1584.      */
  1585.     protected function prepareBaseUrl(): string
  1586.     {
  1587.         $filename basename($this->server->get('SCRIPT_FILENAME'''));
  1588.         if (basename($this->server->get('SCRIPT_NAME''')) === $filename) {
  1589.             $baseUrl $this->server->get('SCRIPT_NAME');
  1590.         } elseif (basename($this->server->get('PHP_SELF''')) === $filename) {
  1591.             $baseUrl $this->server->get('PHP_SELF');
  1592.         } elseif (basename($this->server->get('ORIG_SCRIPT_NAME''')) === $filename) {
  1593.             $baseUrl $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  1594.         } else {
  1595.             // Backtrack up the script_filename to find the portion matching
  1596.             // php_self
  1597.             $path $this->server->get('PHP_SELF''');
  1598.             $file $this->server->get('SCRIPT_FILENAME''');
  1599.             $segs explode('/'trim($file'/'));
  1600.             $segs array_reverse($segs);
  1601.             $index 0;
  1602.             $last \count($segs);
  1603.             $baseUrl '';
  1604.             do {
  1605.                 $seg $segs[$index];
  1606.                 $baseUrl '/'.$seg.$baseUrl;
  1607.                 ++$index;
  1608.             } while ($last $index && (false !== $pos strpos($path$baseUrl)) && != $pos);
  1609.         }
  1610.         // Does the baseUrl have anything in common with the request_uri?
  1611.         $requestUri $this->getRequestUri();
  1612.         if ('' !== $requestUri && '/' !== $requestUri[0]) {
  1613.             $requestUri '/'.$requestUri;
  1614.         }
  1615.         if ($baseUrl && null !== $prefix $this->getUrlencodedPrefix($requestUri$baseUrl)) {
  1616.             // full $baseUrl matches
  1617.             return $prefix;
  1618.         }
  1619.         if ($baseUrl && null !== $prefix $this->getUrlencodedPrefix($requestUrirtrim(\dirname($baseUrl), '/'.\DIRECTORY_SEPARATOR).'/')) {
  1620.             // directory portion of $baseUrl matches
  1621.             return rtrim($prefix'/'.\DIRECTORY_SEPARATOR);
  1622.         }
  1623.         $truncatedRequestUri $requestUri;
  1624.         if (false !== $pos strpos($requestUri'?')) {
  1625.             $truncatedRequestUri substr($requestUri0$pos);
  1626.         }
  1627.         $basename basename($baseUrl ?? '');
  1628.         if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
  1629.             // no match whatsoever; set it blank
  1630.             return '';
  1631.         }
  1632.         // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  1633.         // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  1634.         // from PATH_INFO or QUERY_STRING
  1635.         if (\strlen($requestUri) >= \strlen($baseUrl) && (false !== $pos strpos($requestUri$baseUrl)) && !== $pos) {
  1636.             $baseUrl substr($requestUri0$pos \strlen($baseUrl));
  1637.         }
  1638.         return rtrim($baseUrl'/'.\DIRECTORY_SEPARATOR);
  1639.     }
  1640.     /**
  1641.      * Prepares the base path.
  1642.      */
  1643.     protected function prepareBasePath(): string
  1644.     {
  1645.         $baseUrl $this->getBaseUrl();
  1646.         if (empty($baseUrl)) {
  1647.             return '';
  1648.         }
  1649.         $filename basename($this->server->get('SCRIPT_FILENAME'));
  1650.         if (basename($baseUrl) === $filename) {
  1651.             $basePath \dirname($baseUrl);
  1652.         } else {
  1653.             $basePath $baseUrl;
  1654.         }
  1655.         if ('\\' === \DIRECTORY_SEPARATOR) {
  1656.             $basePath str_replace('\\''/'$basePath);
  1657.         }
  1658.         return rtrim($basePath'/');
  1659.     }
  1660.     /**
  1661.      * Prepares the path info.
  1662.      */
  1663.     protected function preparePathInfo(): string
  1664.     {
  1665.         if (null === ($requestUri $this->getRequestUri())) {
  1666.             return '/';
  1667.         }
  1668.         // Remove the query string from REQUEST_URI
  1669.         if (false !== $pos strpos($requestUri'?')) {
  1670.             $requestUri substr($requestUri0$pos);
  1671.         }
  1672.         if ('' !== $requestUri && '/' !== $requestUri[0]) {
  1673.             $requestUri '/'.$requestUri;
  1674.         }
  1675.         if (null === ($baseUrl $this->getBaseUrlReal())) {
  1676.             return $requestUri;
  1677.         }
  1678.         $pathInfo substr($requestUri\strlen($baseUrl));
  1679.         if (false === $pathInfo || '' === $pathInfo || '/' !== $pathInfo[0]) {
  1680.             return '/'.$pathInfo;
  1681.         }
  1682.         return $pathInfo;
  1683.     }
  1684.     /**
  1685.      * Initializes HTTP request formats.
  1686.      *
  1687.      * @return void
  1688.      */
  1689.     protected static function initializeFormats()
  1690.     {
  1691.         static::$formats = [
  1692.             'html' => ['text/html''application/xhtml+xml'],
  1693.             'txt' => ['text/plain'],
  1694.             'js' => ['application/javascript''application/x-javascript''text/javascript'],
  1695.             'css' => ['text/css'],
  1696.             'json' => ['application/json''application/x-json'],
  1697.             'jsonld' => ['application/ld+json'],
  1698.             'xml' => ['text/xml''application/xml''application/x-xml'],
  1699.             'rdf' => ['application/rdf+xml'],
  1700.             'atom' => ['application/atom+xml'],
  1701.             'rss' => ['application/rss+xml'],
  1702.             'form' => ['application/x-www-form-urlencoded''multipart/form-data'],
  1703.         ];
  1704.     }
  1705.     private function setPhpDefaultLocale(string $locale): void
  1706.     {
  1707.         // if either the class Locale doesn't exist, or an exception is thrown when
  1708.         // setting the default locale, the intl module is not installed, and
  1709.         // the call can be ignored:
  1710.         try {
  1711.             if (class_exists(\Locale::class, false)) {
  1712.                 \Locale::setDefault($locale);
  1713.             }
  1714.         } catch (\Exception) {
  1715.         }
  1716.     }
  1717.     /**
  1718.      * Returns the prefix as encoded in the string when the string starts with
  1719.      * the given prefix, null otherwise.
  1720.      */
  1721.     private function getUrlencodedPrefix(string $stringstring $prefix): ?string
  1722.     {
  1723.         if ($this->isIisRewrite()) {
  1724.             // ISS with UrlRewriteModule might report SCRIPT_NAME/PHP_SELF with wrong case
  1725.             // see https://github.com/php/php-src/issues/11981
  1726.             if (!== stripos(rawurldecode($string), $prefix)) {
  1727.                 return null;
  1728.             }
  1729.         } elseif (!str_starts_with(rawurldecode($string), $prefix)) {
  1730.             return null;
  1731.         }
  1732.         $len \strlen($prefix);
  1733.         if (preg_match(\sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#'$len), $string$match)) {
  1734.             return $match[0];
  1735.         }
  1736.         return null;
  1737.     }
  1738.     private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content null): static
  1739.     {
  1740.         if (self::$requestFactory) {
  1741.             $request = (self::$requestFactory)($query$request$attributes$cookies$files$server$content);
  1742.             if (!$request instanceof self) {
  1743.                 throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
  1744.             }
  1745.             return $request;
  1746.         }
  1747.         return new static($query$request$attributes$cookies$files$server$content);
  1748.     }
  1749.     /**
  1750.      * Indicates whether this request originated from a trusted proxy.
  1751.      *
  1752.      * This can be useful to determine whether or not to trust the
  1753.      * contents of a proxy-specific header.
  1754.      */
  1755.     public function isFromTrustedProxy(): bool
  1756.     {
  1757.         return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'''), self::$trustedProxies);
  1758.     }
  1759.     /**
  1760.      * This method is rather heavy because it splits and merges headers, and it's called by many other methods such as
  1761.      * getPort(), isSecure(), getHost(), getClientIps(), getBaseUrl() etc. Thus, we try to cache the results for
  1762.      * best performance.
  1763.      */
  1764.     private function getTrustedValues(int $type, ?string $ip null): array
  1765.     {
  1766.         $cacheKey $type."\0".((self::$trustedHeaderSet $type) ? $this->headers->get(self::TRUSTED_HEADERS[$type]) : '');
  1767.         $cacheKey .= "\0".$ip."\0".$this->headers->get(self::TRUSTED_HEADERS[self::HEADER_FORWARDED]);
  1768.         if (isset($this->trustedValuesCache[$cacheKey])) {
  1769.             return $this->trustedValuesCache[$cacheKey];
  1770.         }
  1771.         $clientValues = [];
  1772.         $forwardedValues = [];
  1773.         if ((self::$trustedHeaderSet $type) && $this->headers->has(self::TRUSTED_HEADERS[$type])) {
  1774.             foreach (explode(','$this->headers->get(self::TRUSTED_HEADERS[$type])) as $v) {
  1775.                 $clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type '0.0.0.0:' '').trim($v);
  1776.             }
  1777.         }
  1778.         if ((self::$trustedHeaderSet self::HEADER_FORWARDED) && (isset(self::FORWARDED_PARAMS[$type])) && $this->headers->has(self::TRUSTED_HEADERS[self::HEADER_FORWARDED])) {
  1779.             $forwarded $this->headers->get(self::TRUSTED_HEADERS[self::HEADER_FORWARDED]);
  1780.             $parts HeaderUtils::split($forwarded',;=');
  1781.             $param self::FORWARDED_PARAMS[$type];
  1782.             foreach ($parts as $subParts) {
  1783.                 if (null === $v HeaderUtils::combine($subParts)[$param] ?? null) {
  1784.                     continue;
  1785.                 }
  1786.                 if (self::HEADER_X_FORWARDED_PORT === $type) {
  1787.                     if (str_ends_with($v']') || false === $v strrchr($v':')) {
  1788.                         $v $this->isSecure() ? ':443' ':80';
  1789.                     }
  1790.                     $v '0.0.0.0'.$v;
  1791.                 }
  1792.                 $forwardedValues[] = $v;
  1793.             }
  1794.         }
  1795.         if (null !== $ip) {
  1796.             $clientValues $this->normalizeAndFilterClientIps($clientValues$ip);
  1797.             $forwardedValues $this->normalizeAndFilterClientIps($forwardedValues$ip);
  1798.         }
  1799.         if ($forwardedValues === $clientValues || !$clientValues) {
  1800.             return $this->trustedValuesCache[$cacheKey] = $forwardedValues;
  1801.         }
  1802.         if (!$forwardedValues) {
  1803.             return $this->trustedValuesCache[$cacheKey] = $clientValues;
  1804.         }
  1805.         if (!$this->isForwardedValid) {
  1806.             return $this->trustedValuesCache[$cacheKey] = null !== $ip ? ['0.0.0.0'$ip] : [];
  1807.         }
  1808.         $this->isForwardedValid false;
  1809.         throw new ConflictingHeadersException(\sprintf('The request has both a trusted "%s" header and a trusted "%s" header, conflicting with each other. You should either configure your proxy to remove one of them, or configure your project to distrust the offending one.'self::TRUSTED_HEADERS[self::HEADER_FORWARDED], self::TRUSTED_HEADERS[$type]));
  1810.     }
  1811.     private function normalizeAndFilterClientIps(array $clientIpsstring $ip): array
  1812.     {
  1813.         if (!$clientIps) {
  1814.             return [];
  1815.         }
  1816.         $clientIps[] = $ip// Complete the IP chain with the IP the request actually came from
  1817.         $firstTrustedIp null;
  1818.         foreach ($clientIps as $key => $clientIp) {
  1819.             if (strpos($clientIp'.')) {
  1820.                 // Strip :port from IPv4 addresses. This is allowed in Forwarded
  1821.                 // and may occur in X-Forwarded-For.
  1822.                 $i strpos($clientIp':');
  1823.                 if ($i) {
  1824.                     $clientIps[$key] = $clientIp substr($clientIp0$i);
  1825.                 }
  1826.             } elseif (str_starts_with($clientIp'[')) {
  1827.                 // Strip brackets and :port from IPv6 addresses.
  1828.                 $i strpos($clientIp']'1);
  1829.                 $clientIps[$key] = $clientIp substr($clientIp1$i 1);
  1830.             }
  1831.             if (!filter_var($clientIp\FILTER_VALIDATE_IP)) {
  1832.                 unset($clientIps[$key]);
  1833.                 continue;
  1834.             }
  1835.             if (IpUtils::checkIp($clientIpself::$trustedProxies)) {
  1836.                 unset($clientIps[$key]);
  1837.                 // Fallback to this when the client IP falls into the range of trusted proxies
  1838.                 $firstTrustedIp ??= $clientIp;
  1839.             }
  1840.         }
  1841.         // Now the IP chain contains only untrusted proxies and the client IP
  1842.         return $clientIps array_reverse($clientIps) : [$firstTrustedIp];
  1843.     }
  1844.     /**
  1845.      * Is this IIS with UrlRewriteModule?
  1846.      *
  1847.      * This method consumes, caches and removed the IIS_WasUrlRewritten env var,
  1848.      * so we don't inherit it to sub-requests.
  1849.      */
  1850.     private function isIisRewrite(): bool
  1851.     {
  1852.         if (=== $this->server->getInt('IIS_WasUrlRewritten')) {
  1853.             $this->isIisRewrite true;
  1854.             $this->server->remove('IIS_WasUrlRewritten');
  1855.         }
  1856.         return $this->isIisRewrite;
  1857.     }
  1858.     /**
  1859.      * See https://url.spec.whatwg.org/.
  1860.      */
  1861.     private static function isHostValid(string $host): bool
  1862.     {
  1863.         if ('[' === $host[0]) {
  1864.             return ']' === $host[-1] && filter_var(substr($host1, -1), \FILTER_VALIDATE_IP\FILTER_FLAG_IPV6);
  1865.         }
  1866.         if (preg_match('/\.[0-9]++\.?$/D'$host)) {
  1867.             return null !== filter_var($host\FILTER_VALIDATE_IP\FILTER_FLAG_IPV4 \FILTER_NULL_ON_FAILURE);
  1868.         }
  1869.         // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
  1870.         return '' === preg_replace('/[-a-zA-Z0-9_]++\.?/'''$host);
  1871.     }
  1872. }