PrefixTrait.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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\Loader\Configurator\Traits;
  11. use Symfony\Component\Routing\Route;
  12. use Symfony\Component\Routing\RouteCollection;
  13. /**
  14. * @internal
  15. *
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. trait PrefixTrait
  19. {
  20. final protected function addPrefix(RouteCollection $routes, string|array $prefix, bool $trailingSlashOnRoot): void
  21. {
  22. if (\is_array($prefix)) {
  23. foreach ($prefix as $locale => $localePrefix) {
  24. $prefix[$locale] = trim(trim($localePrefix), '/');
  25. }
  26. $aliases = [];
  27. foreach ($routes->getAliases() as $name => $alias) {
  28. $aliases[$alias->getId()][] = $name;
  29. }
  30. foreach ($routes->all() as $name => $route) {
  31. if (null === $locale = $route->getDefault('_locale')) {
  32. $priority = $routes->getPriority($name) ?? 0;
  33. $routes->remove($name);
  34. foreach ($aliases[$name] ?? [] as $aliasName) {
  35. $routes->remove($aliasName);
  36. }
  37. foreach ($prefix as $locale => $localePrefix) {
  38. $localizedRoute = clone $route;
  39. $localizedRoute->setDefault('_locale', $locale);
  40. $localizedRoute->setRequirement('_locale', preg_quote($locale));
  41. $localizedRoute->setDefault('_canonical_route', $name);
  42. $localizedRoute->setPath($localePrefix.(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  43. $routes->add($name.'.'.$locale, $localizedRoute, $priority);
  44. foreach ($aliases[$name] ?? [] as $aliasName) {
  45. $routes->addAlias($aliasName.'.'.$locale, $name.'.'.$locale);
  46. }
  47. }
  48. } elseif (!isset($prefix[$locale])) {
  49. throw new \InvalidArgumentException(\sprintf('Route "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $name, $locale));
  50. } else {
  51. $route->setPath($prefix[$locale].(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  52. $routes->add($name, $route, $routes->getPriority($name) ?? 0);
  53. }
  54. }
  55. return;
  56. }
  57. $routes->addPrefix($prefix);
  58. if (!$trailingSlashOnRoot) {
  59. $rootPath = (new Route(trim(trim($prefix), '/').'/'))->getPath();
  60. foreach ($routes->all() as $route) {
  61. if ($route->getPath() === $rootPath) {
  62. $route->setPath(rtrim($rootPath, '/'));
  63. }
  64. }
  65. }
  66. }
  67. }