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

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