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

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