CurrentPathStack.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Drupal\Core\Path;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\RequestStack;
  5. /**
  6. * Represents the current path for the current request.
  7. *
  8. * Note: You should not rely on paths but rather on route names / parameters or
  9. * other indicators like context. For some fundamental parts, like routing or
  10. * path processing, there is unfortunately no way around dealing with paths.
  11. */
  12. class CurrentPathStack {
  13. /**
  14. * Static cache of paths.
  15. *
  16. * @var \SplObjectStorage
  17. */
  18. protected $paths;
  19. /**
  20. * The request stack.
  21. *
  22. * @var \Symfony\Component\HttpFoundation\RequestStack
  23. */
  24. protected $requestStack;
  25. /**
  26. * Constructs a new CurrentPathStack instance.
  27. *
  28. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  29. * The request stack.
  30. */
  31. public function __construct(RequestStack $request_stack) {
  32. $this->requestStack = $request_stack;
  33. $this->paths = new \SplObjectStorage();
  34. }
  35. /**
  36. * Returns the path of the current request.
  37. *
  38. * @param \Symfony\Component\HttpFoundation\Request $request
  39. * (optional) The request.
  40. *
  41. * @return string
  42. * Returns the path, without leading slashes.
  43. */
  44. public function getPath(Request $request = NULL) {
  45. if (!isset($request)) {
  46. $request = $this->requestStack->getCurrentRequest();
  47. }
  48. if (!isset($this->paths[$request])) {
  49. $this->paths[$request] = $request->getPathInfo();
  50. }
  51. return $this->paths[$request];
  52. }
  53. /**
  54. * Sets the current path.
  55. *
  56. * @param string $path
  57. * The path.
  58. * @param \Symfony\Component\HttpFoundation\Request $request
  59. * (optional) The request.
  60. *
  61. * @return $this
  62. */
  63. public function setPath($path, Request $request = NULL) {
  64. if (!isset($request)) {
  65. $request = $this->requestStack->getCurrentRequest();
  66. }
  67. $this->paths[$request] = $path;
  68. return $this;
  69. }
  70. }