No Description

DumperPrefixCollection.php 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. for ($collection = $this; null !== $collection; $collection = $collection->getParent()) {
  53. // Same prefix, add to current leave
  54. if ($collection->prefix === $prefix) {
  55. $collection->add($route);
  56. return $collection;
  57. }
  58. // Prefix starts with route's prefix
  59. if ('' === $collection->prefix || 0 === strpos($prefix, $collection->prefix)) {
  60. $child = new DumperPrefixCollection();
  61. $child->setPrefix(substr($prefix, 0, strlen($collection->prefix)+1));
  62. $collection->add($child);
  63. return $child->addPrefixRoute($route);
  64. }
  65. }
  66. // Reached only if the root has a non empty prefix
  67. throw new \LogicException("The collection root must not have a prefix");
  68. }
  69. /**
  70. * Merges nodes whose prefix ends with a slash.
  71. *
  72. * Children of a node whose prefix ends with a slash are moved to the parent node
  73. */
  74. public function mergeSlashNodes()
  75. {
  76. $children = array();
  77. foreach ($this as $child) {
  78. if ($child instanceof self) {
  79. $child->mergeSlashNodes();
  80. if ('/' === substr($child->prefix, -1)) {
  81. $children = array_merge($children, $child->all());
  82. } else {
  83. $children[] = $child;
  84. }
  85. } else {
  86. $children[] = $child;
  87. }
  88. }
  89. $this->setAll($children);
  90. }
  91. }