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

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