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

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