DumperPrefixCollection.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Routing\Matcher\Dumper;
  11. /**
  12. * Prefix tree of routes preserving routes order.
  13. *
  14. * @author Arnaud Le Blanc <arnaud.lb@gmail.com>
  15. */
  16. class DumperPrefixCollection extends DumperCollection
  17. {
  18. /**
  19. * @var string
  20. */
  21. private $prefix = '';
  22. /**
  23. * Returns the prefix.
  24. *
  25. * @return string The prefix
  26. */
  27. public function getPrefix()
  28. {
  29. return $this->prefix;
  30. }
  31. /**
  32. * Sets the prefix.
  33. *
  34. * @param string $prefix The prefix
  35. */
  36. public function setPrefix($prefix)
  37. {
  38. $this->prefix = $prefix;
  39. }
  40. /**
  41. * Adds a route in the tree.
  42. *
  43. * @param DumperRoute $route The route
  44. *
  45. * @return DumperPrefixCollection The node the route was added to
  46. *
  47. * @throws \LogicException
  48. */
  49. public function addPrefixRoute(DumperRoute $route)
  50. {
  51. $prefix = $route->getRoute()->compile()->getStaticPrefix();
  52. // Same prefix, add to current leave
  53. if ($this->prefix === $prefix) {
  54. $this->add($route);
  55. return $this;
  56. }
  57. // Prefix starts with route's prefix
  58. if ('' === $this->prefix || 0 === strpos($prefix, $this->prefix)) {
  59. $collection = new DumperPrefixCollection();
  60. $collection->setPrefix(substr($prefix, 0, strlen($this->prefix)+1));
  61. $this->add($collection);
  62. return $collection->addPrefixRoute($route);
  63. }
  64. // No match, fallback to parent (recursively)
  65. if (null === $parent = $this->getParent()) {
  66. throw new \LogicException("The collection root must not have a prefix");
  67. }
  68. return $parent->addPrefixRoute($route);
  69. }
  70. /**
  71. * Merges nodes whose prefix ends with a slash
  72. *
  73. * Children of a node whose prefix ends with a slash are moved to the parent node
  74. */
  75. public function mergeSlashNodes()
  76. {
  77. $children = array();
  78. foreach ($this as $child) {
  79. if ($child instanceof self) {
  80. $child->mergeSlashNodes();
  81. if ('/' === substr($child->prefix, -1)) {
  82. $children = array_merge($children, $child->all());
  83. } else {
  84. $children[] = $child;
  85. }
  86. } else {
  87. $children[] = $child;
  88. }
  89. }
  90. $this->setAll($children);
  91. }
  92. }