PrefixTrait.php 2.3 KB

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