LocalizedRouteTrait.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. * @author Jules Pietri <jules@heahprod.com>
  18. */
  19. trait LocalizedRouteTrait
  20. {
  21. /**
  22. * Creates one or many routes.
  23. *
  24. * @param string|array $path the path, or the localized paths of the route
  25. */
  26. final protected function createLocalizedRoute(RouteCollection $collection, string $name, $path, string $namePrefix = '', array $prefixes = null): RouteCollection
  27. {
  28. $paths = [];
  29. $routes = new RouteCollection();
  30. if (\is_array($path)) {
  31. if (null === $prefixes) {
  32. $paths = $path;
  33. } elseif ($missing = array_diff_key($prefixes, $path)) {
  34. throw new \LogicException(sprintf('Route "%s" is missing routes for locale(s) "%s".', $name, implode('", "', array_keys($missing))));
  35. } else {
  36. foreach ($path as $locale => $localePath) {
  37. if (!isset($prefixes[$locale])) {
  38. throw new \LogicException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $name, $locale));
  39. }
  40. $paths[$locale] = $prefixes[$locale].$localePath;
  41. }
  42. }
  43. } elseif (null !== $prefixes) {
  44. foreach ($prefixes as $locale => $prefix) {
  45. $paths[$locale] = $prefix.$path;
  46. }
  47. } else {
  48. $routes->add($namePrefix.$name, $route = $this->createRoute($path));
  49. $collection->add($namePrefix.$name, $route);
  50. return $routes;
  51. }
  52. foreach ($paths as $locale => $path) {
  53. $routes->add($name.'.'.$locale, $route = $this->createRoute($path));
  54. $collection->add($namePrefix.$name.'.'.$locale, $route);
  55. $route->setDefault('_locale', $locale);
  56. $route->setRequirement('_locale', preg_quote($locale));
  57. $route->setDefault('_canonical_route', $namePrefix.$name);
  58. }
  59. return $routes;
  60. }
  61. private function createRoute(string $path): Route
  62. {
  63. return new Route($path);
  64. }
  65. }