HostTrait.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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\RouteCollection;
  12. /**
  13. * @internal
  14. */
  15. trait HostTrait
  16. {
  17. final protected function addHost(RouteCollection $routes, $hosts)
  18. {
  19. if (!$hosts || !\is_array($hosts)) {
  20. $routes->setHost($hosts ?: '');
  21. return;
  22. }
  23. foreach ($routes->all() as $name => $route) {
  24. if (null === $locale = $route->getDefault('_locale')) {
  25. $priority = $routes->getPriority($name) ?? 0;
  26. $routes->remove($name);
  27. foreach ($hosts as $locale => $host) {
  28. $localizedRoute = clone $route;
  29. $localizedRoute->setDefault('_locale', $locale);
  30. $localizedRoute->setRequirement('_locale', preg_quote($locale));
  31. $localizedRoute->setDefault('_canonical_route', $name);
  32. $localizedRoute->setHost($host);
  33. $routes->add($name.'.'.$locale, $localizedRoute, $priority);
  34. }
  35. } elseif (!isset($hosts[$locale])) {
  36. throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding host in its parent collection.', $name, $locale));
  37. } else {
  38. $route->setHost($hosts[$locale]);
  39. $route->setRequirement('_locale', preg_quote($locale));
  40. $routes->add($name, $route, $routes->getPriority($name) ?? 0);
  41. }
  42. }
  43. }
  44. }