LocalAwareRedirectResponseTrait.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Drupal\Core\Routing;
  3. use Drupal\Component\Utility\UrlHelper;
  4. /**
  5. * Provides a trait which ensures that a URL is safe to redirect to.
  6. */
  7. trait LocalAwareRedirectResponseTrait {
  8. /**
  9. * The request context.
  10. *
  11. * @var \Drupal\Core\Routing\RequestContext
  12. */
  13. protected $requestContext;
  14. /**
  15. * Determines whether a path is local.
  16. *
  17. * @param string $url
  18. * The internal path or external URL being linked to, such as "node/34" or
  19. * "http://example.com/foo".
  20. *
  21. * @return bool
  22. * TRUE or FALSE, where TRUE indicates a local path.
  23. */
  24. protected function isLocal($url) {
  25. return !UrlHelper::isExternal($url) || UrlHelper::externalIsLocal($url, $this->getRequestContext()->getCompleteBaseUrl());
  26. }
  27. /**
  28. * Returns the request context.
  29. *
  30. * @return \Drupal\Core\Routing\RequestContext
  31. * The request context.
  32. */
  33. protected function getRequestContext() {
  34. if (!isset($this->requestContext)) {
  35. $this->requestContext = \Drupal::service('router.request_context');
  36. }
  37. return $this->requestContext;
  38. }
  39. /**
  40. * Sets the request context.
  41. *
  42. * @param \Drupal\Core\Routing\RequestContext $request_context
  43. * The request context.
  44. *
  45. * @return $this
  46. */
  47. public function setRequestContext(RequestContext $request_context) {
  48. $this->requestContext = $request_context;
  49. return $this;
  50. }
  51. }