HostTrait.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. $routes->remove($name);
  26. foreach ($hosts as $locale => $host) {
  27. $localizedRoute = clone $route;
  28. $localizedRoute->setDefault('_locale', $locale);
  29. $localizedRoute->setRequirement('_locale', preg_quote($locale));
  30. $localizedRoute->setDefault('_canonical_route', $name);
  31. $localizedRoute->setHost($host);
  32. $routes->add($name.'.'.$locale, $localizedRoute);
  33. }
  34. } elseif (!isset($hosts[$locale])) {
  35. throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding host in its parent collection.', $name, $locale));
  36. } else {
  37. $route->setHost($hosts[$locale]);
  38. $route->setRequirement('_locale', preg_quote($locale));
  39. $routes->add($name, $route);
  40. }
  41. }
  42. }
  43. }