PrefixTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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, $prefix, bool $trailingSlashOnRoot)
  21. {
  22. if (\is_array($prefix)) {
  23. foreach ($prefix as $locale => $localePrefix) {
  24. $prefix[$locale] = trim(trim($localePrefix), '/');
  25. }
  26. foreach ($routes->all() as $name => $route) {
  27. if (null === $locale = $route->getDefault('_locale')) {
  28. $priority = $routes->getPriority($name) ?? 0;
  29. $routes->remove($name);
  30. foreach ($prefix as $locale => $localePrefix) {
  31. $localizedRoute = clone $route;
  32. $localizedRoute->setDefault('_locale', $locale);
  33. $localizedRoute->setRequirement('_locale', preg_quote($locale));
  34. $localizedRoute->setDefault('_canonical_route', $name);
  35. $localizedRoute->setPath($localePrefix.(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  36. $routes->add($name.'.'.$locale, $localizedRoute, $priority);
  37. }
  38. } elseif (!isset($prefix[$locale])) {
  39. throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $name, $locale));
  40. } else {
  41. $route->setPath($prefix[$locale].(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  42. $routes->add($name, $route, $routes->getPriority($name) ?? 0);
  43. }
  44. }
  45. return;
  46. }
  47. $routes->addPrefix($prefix);
  48. if (!$trailingSlashOnRoot) {
  49. $rootPath = (new Route(trim(trim($prefix), '/').'/'))->getPath();
  50. foreach ($routes->all() as $route) {
  51. if ($route->getPath() === $rootPath) {
  52. $route->setPath(rtrim($rootPath, '/'));
  53. }
  54. }
  55. }
  56. }
  57. }