RedirectDestinationTrait.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\Core\Routing;
  3. /**
  4. * Wrapper methods for the Redirect Destination.
  5. *
  6. * This utility trait should only be used in application-level code, such as
  7. * classes that would implement ContainerInjectionInterface. Services registered
  8. * in the Container should not use this trait but inject the appropriate service
  9. * directly for easier testing.
  10. */
  11. trait RedirectDestinationTrait {
  12. /**
  13. * The redirect destination service.
  14. *
  15. * @var \Drupal\Core\Routing\RedirectDestinationInterface
  16. */
  17. protected $redirectDestination;
  18. /**
  19. * Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
  20. *
  21. * @see \Drupal\Core\Routing\RedirectDestinationInterface::getAsArray()
  22. *
  23. * @return array
  24. * An associative array containing the key:
  25. * - destination: The value of the current request's 'destination' query
  26. * parameter, if present. This can be either a relative or absolute URL.
  27. * However, for security, redirection to external URLs is not performed.
  28. * If the query parameter isn't present, then the URL of the current
  29. * request is returned.
  30. */
  31. protected function getDestinationArray() {
  32. return $this->getRedirectDestination()->getAsArray();
  33. }
  34. /**
  35. * Returns the redirect destination service.
  36. *
  37. * @return \Drupal\Core\Routing\RedirectDestinationInterface
  38. * The redirect destination helper.
  39. */
  40. protected function getRedirectDestination() {
  41. if (!isset($this->redirectDestination)) {
  42. $this->redirectDestination = \Drupal::destination();
  43. }
  44. return $this->redirectDestination;
  45. }
  46. /**
  47. * Sets the redirect destination service.
  48. *
  49. * @param \Drupal\Core\Routing\RedirectDestinationInterface $redirect_destination
  50. * The redirect destination service.
  51. *
  52. * @return $this
  53. */
  54. public function setRedirectDestination(RedirectDestinationInterface $redirect_destination) {
  55. $this->redirectDestination = $redirect_destination;
  56. return $this;
  57. }
  58. }