TrustedRedirectResponse.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Drupal\Core\Routing;
  3. /**
  4. * Provides a redirect response which contains trusted URLs.
  5. *
  6. * Use this class in case you know that you want to redirect to an external URL.
  7. */
  8. class TrustedRedirectResponse extends CacheableSecuredRedirectResponse {
  9. use LocalAwareRedirectResponseTrait;
  10. /**
  11. * A list of trusted URLs, which are safe to redirect to.
  12. *
  13. * @var string[]
  14. */
  15. protected $trustedUrls = [];
  16. /**
  17. * {@inheritdoc}
  18. */
  19. public function __construct($url, $status = 302, $headers = []) {
  20. $this->trustedUrls[$url] = TRUE;
  21. parent::__construct($url, $status, $headers);
  22. }
  23. /**
  24. * Sets the target URL to a trusted URL.
  25. *
  26. * @param string $url
  27. * A trusted URL.
  28. *
  29. * @return $this
  30. */
  31. public function setTrustedTargetUrl($url) {
  32. $this->trustedUrls[$url] = TRUE;
  33. return $this->setTargetUrl($url);
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. protected function isSafe($url) {
  39. return !empty($this->trustedUrls[$url]) || $this->isLocal($url);
  40. }
  41. }