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

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