RouteCollection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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;
  11. use Symfony\Component\Config\Resource\ResourceInterface;
  12. use Symfony\Component\Routing\Exception\InvalidArgumentException;
  13. use Symfony\Component\Routing\Exception\RouteCircularReferenceException;
  14. /**
  15. * A RouteCollection represents a set of Route instances.
  16. *
  17. * When adding a route at the end of the collection, an existing route
  18. * with the same name is removed first. So there can only be one route
  19. * with a given name.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. * @author Tobias Schultze <http://tobion.de>
  23. *
  24. * @implements \IteratorAggregate<string, Route>
  25. */
  26. class RouteCollection implements \IteratorAggregate, \Countable
  27. {
  28. /**
  29. * @var array<string, Route>
  30. */
  31. private $routes = [];
  32. /**
  33. * @var array<string, Alias>
  34. */
  35. private $aliases = [];
  36. /**
  37. * @var array<string, ResourceInterface>
  38. */
  39. private $resources = [];
  40. /**
  41. * @var array<string, int>
  42. */
  43. private $priorities = [];
  44. public function __clone()
  45. {
  46. foreach ($this->routes as $name => $route) {
  47. $this->routes[$name] = clone $route;
  48. }
  49. foreach ($this->aliases as $name => $alias) {
  50. $this->aliases[$name] = clone $alias;
  51. }
  52. }
  53. /**
  54. * Gets the current RouteCollection as an Iterator that includes all routes.
  55. *
  56. * It implements \IteratorAggregate.
  57. *
  58. * @see all()
  59. *
  60. * @return \ArrayIterator<string, Route>
  61. */
  62. #[\ReturnTypeWillChange]
  63. public function getIterator()
  64. {
  65. return new \ArrayIterator($this->all());
  66. }
  67. /**
  68. * Gets the number of Routes in this collection.
  69. *
  70. * @return int
  71. */
  72. #[\ReturnTypeWillChange]
  73. public function count()
  74. {
  75. return \count($this->routes);
  76. }
  77. /**
  78. * @param int $priority
  79. */
  80. public function add(string $name, Route $route/* , int $priority = 0 */)
  81. {
  82. if (\func_num_args() < 3 && __CLASS__ !== static::class && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface && !$this instanceof \Mockery\MockInterface) {
  83. trigger_deprecation('symfony/routing', '5.1', 'The "%s()" method will have a new "int $priority = 0" argument in version 6.0, not defining it is deprecated.', __METHOD__);
  84. }
  85. unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]);
  86. $this->routes[$name] = $route;
  87. if ($priority = 3 <= \func_num_args() ? func_get_arg(2) : 0) {
  88. $this->priorities[$name] = $priority;
  89. }
  90. }
  91. /**
  92. * Returns all routes in this collection.
  93. *
  94. * @return array<string, Route>
  95. */
  96. public function all()
  97. {
  98. if ($this->priorities) {
  99. $priorities = $this->priorities;
  100. $keysOrder = array_flip(array_keys($this->routes));
  101. uksort($this->routes, static function ($n1, $n2) use ($priorities, $keysOrder) {
  102. return (($priorities[$n2] ?? 0) <=> ($priorities[$n1] ?? 0)) ?: ($keysOrder[$n1] <=> $keysOrder[$n2]);
  103. });
  104. }
  105. return $this->routes;
  106. }
  107. /**
  108. * Gets a route by name.
  109. *
  110. * @return Route|null
  111. */
  112. public function get(string $name)
  113. {
  114. $visited = [];
  115. while (null !== $alias = $this->aliases[$name] ?? null) {
  116. if (false !== $searchKey = array_search($name, $visited)) {
  117. $visited[] = $name;
  118. throw new RouteCircularReferenceException($name, \array_slice($visited, $searchKey));
  119. }
  120. if ($alias->isDeprecated()) {
  121. $deprecation = $alias->getDeprecation($name);
  122. trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']);
  123. }
  124. $visited[] = $name;
  125. $name = $alias->getId();
  126. }
  127. return $this->routes[$name] ?? null;
  128. }
  129. /**
  130. * Removes a route or an array of routes by name from the collection.
  131. *
  132. * @param string|string[] $name The route name or an array of route names
  133. */
  134. public function remove($name)
  135. {
  136. foreach ((array) $name as $n) {
  137. unset($this->routes[$n], $this->priorities[$n], $this->aliases[$n]);
  138. }
  139. }
  140. /**
  141. * Adds a route collection at the end of the current set by appending all
  142. * routes of the added collection.
  143. */
  144. public function addCollection(self $collection)
  145. {
  146. // we need to remove all routes with the same names first because just replacing them
  147. // would not place the new route at the end of the merged array
  148. foreach ($collection->all() as $name => $route) {
  149. unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]);
  150. $this->routes[$name] = $route;
  151. if (isset($collection->priorities[$name])) {
  152. $this->priorities[$name] = $collection->priorities[$name];
  153. }
  154. }
  155. foreach ($collection->getAliases() as $name => $alias) {
  156. unset($this->routes[$name], $this->priorities[$name], $this->aliases[$name]);
  157. $this->aliases[$name] = $alias;
  158. }
  159. foreach ($collection->getResources() as $resource) {
  160. $this->addResource($resource);
  161. }
  162. }
  163. /**
  164. * Adds a prefix to the path of all child routes.
  165. */
  166. public function addPrefix(string $prefix, array $defaults = [], array $requirements = [])
  167. {
  168. $prefix = trim(trim($prefix), '/');
  169. if ('' === $prefix) {
  170. return;
  171. }
  172. foreach ($this->routes as $route) {
  173. $route->setPath('/'.$prefix.$route->getPath());
  174. $route->addDefaults($defaults);
  175. $route->addRequirements($requirements);
  176. }
  177. }
  178. /**
  179. * Adds a prefix to the name of all the routes within in the collection.
  180. */
  181. public function addNamePrefix(string $prefix)
  182. {
  183. $prefixedRoutes = [];
  184. $prefixedPriorities = [];
  185. $prefixedAliases = [];
  186. foreach ($this->routes as $name => $route) {
  187. $prefixedRoutes[$prefix.$name] = $route;
  188. if (null !== $canonicalName = $route->getDefault('_canonical_route')) {
  189. $route->setDefault('_canonical_route', $prefix.$canonicalName);
  190. }
  191. if (isset($this->priorities[$name])) {
  192. $prefixedPriorities[$prefix.$name] = $this->priorities[$name];
  193. }
  194. }
  195. foreach ($this->aliases as $name => $alias) {
  196. $prefixedAliases[$prefix.$name] = $alias->withId($prefix.$alias->getId());
  197. }
  198. $this->routes = $prefixedRoutes;
  199. $this->priorities = $prefixedPriorities;
  200. $this->aliases = $prefixedAliases;
  201. }
  202. /**
  203. * Sets the host pattern on all routes.
  204. */
  205. public function setHost(?string $pattern, array $defaults = [], array $requirements = [])
  206. {
  207. foreach ($this->routes as $route) {
  208. $route->setHost($pattern);
  209. $route->addDefaults($defaults);
  210. $route->addRequirements($requirements);
  211. }
  212. }
  213. /**
  214. * Sets a condition on all routes.
  215. *
  216. * Existing conditions will be overridden.
  217. */
  218. public function setCondition(?string $condition)
  219. {
  220. foreach ($this->routes as $route) {
  221. $route->setCondition($condition);
  222. }
  223. }
  224. /**
  225. * Adds defaults to all routes.
  226. *
  227. * An existing default value under the same name in a route will be overridden.
  228. */
  229. public function addDefaults(array $defaults)
  230. {
  231. if ($defaults) {
  232. foreach ($this->routes as $route) {
  233. $route->addDefaults($defaults);
  234. }
  235. }
  236. }
  237. /**
  238. * Adds requirements to all routes.
  239. *
  240. * An existing requirement under the same name in a route will be overridden.
  241. */
  242. public function addRequirements(array $requirements)
  243. {
  244. if ($requirements) {
  245. foreach ($this->routes as $route) {
  246. $route->addRequirements($requirements);
  247. }
  248. }
  249. }
  250. /**
  251. * Adds options to all routes.
  252. *
  253. * An existing option value under the same name in a route will be overridden.
  254. */
  255. public function addOptions(array $options)
  256. {
  257. if ($options) {
  258. foreach ($this->routes as $route) {
  259. $route->addOptions($options);
  260. }
  261. }
  262. }
  263. /**
  264. * Sets the schemes (e.g. 'https') all child routes are restricted to.
  265. *
  266. * @param string|string[] $schemes The scheme or an array of schemes
  267. */
  268. public function setSchemes($schemes)
  269. {
  270. foreach ($this->routes as $route) {
  271. $route->setSchemes($schemes);
  272. }
  273. }
  274. /**
  275. * Sets the HTTP methods (e.g. 'POST') all child routes are restricted to.
  276. *
  277. * @param string|string[] $methods The method or an array of methods
  278. */
  279. public function setMethods($methods)
  280. {
  281. foreach ($this->routes as $route) {
  282. $route->setMethods($methods);
  283. }
  284. }
  285. /**
  286. * Returns an array of resources loaded to build this collection.
  287. *
  288. * @return ResourceInterface[]
  289. */
  290. public function getResources()
  291. {
  292. return array_values($this->resources);
  293. }
  294. /**
  295. * Adds a resource for this collection. If the resource already exists
  296. * it is not added.
  297. */
  298. public function addResource(ResourceInterface $resource)
  299. {
  300. $key = (string) $resource;
  301. if (!isset($this->resources[$key])) {
  302. $this->resources[$key] = $resource;
  303. }
  304. }
  305. /**
  306. * Sets an alias for an existing route.
  307. *
  308. * @param string $name The alias to create
  309. * @param string $alias The route to alias
  310. *
  311. * @throws InvalidArgumentException if the alias is for itself
  312. */
  313. public function addAlias(string $name, string $alias): Alias
  314. {
  315. if ($name === $alias) {
  316. throw new InvalidArgumentException(sprintf('Route alias "%s" can not reference itself.', $name));
  317. }
  318. unset($this->routes[$name], $this->priorities[$name]);
  319. return $this->aliases[$name] = new Alias($alias);
  320. }
  321. /**
  322. * @return array<string, Alias>
  323. */
  324. public function getAliases(): array
  325. {
  326. return $this->aliases;
  327. }
  328. public function getAlias(string $name): ?Alias
  329. {
  330. return $this->aliases[$name] ?? null;
  331. }
  332. }