TrustedHostsRequestFactory.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\Core\Http;
  3. use Symfony\Component\HttpFoundation\Request;
  4. /**
  5. * Provides a request factory for requests using host verification.
  6. *
  7. * Because the trusted host patterns for requests are stored statically, they
  8. * are consulted even for fake request created with Request::create(), whose
  9. * host is 'localhost' by default. Such requests would fail host verification
  10. * unless 'localhost' matches one of the trusted host patterns. To circumvent
  11. * this problem, this factory injects the server variables from the main request
  12. * into each newly created request, so that the host is correctly set even for
  13. * fake requests and they properly pass host verification.
  14. *
  15. * @see \Drupal\Core\DrupalKernel::setupTrustedHosts()
  16. */
  17. class TrustedHostsRequestFactory {
  18. /**
  19. * The host of the main request.
  20. *
  21. * @var string
  22. */
  23. protected $host;
  24. /**
  25. * Creates a new TrustedHostsRequestFactory.
  26. *
  27. * @param string $host
  28. * The host of the main request.
  29. */
  30. public function __construct($host) {
  31. $this->host = (string) $host;
  32. }
  33. /**
  34. * Creates a new request object.
  35. *
  36. * @param array $query
  37. * (optional) The query (GET) or request (POST) parameters.
  38. * @param array $request
  39. * (optional) An array of request variables.
  40. * @param array $attributes
  41. * (optional) An array of attributes.
  42. * @param array $cookies
  43. * (optional) The request cookies ($_COOKIE).
  44. * @param array $files
  45. * (optional) The request files ($_FILES).
  46. * @param array $server
  47. * (optional) The server parameters ($_SERVER).
  48. * @param string $content
  49. * (optional) The raw body data.
  50. *
  51. * @return \Symfony\Component\HttpFoundation\Request
  52. * A new request object.
  53. */
  54. public function createRequest(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = NULL) {
  55. if (empty($server['HTTP_HOST']) || ($server['HTTP_HOST'] === 'localhost' && $this->host !== 'localhost')) {
  56. $server['HTTP_HOST'] = $this->host;
  57. }
  58. return new Request($query, $request, $attributes, $cookies, $files, $server, $content);
  59. }
  60. }