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

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