|
| 1 | +<?php |
| 2 | +namespace M4nu\MultiDomainBundle\EventListener; |
| 3 | + |
| 4 | +use Symfony\Cmf\Component\Routing\Event\RouterGenerateEvent; |
| 5 | +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; |
| 6 | +use Symfony\Component\Routing\RouterInterface; |
| 7 | + |
| 8 | +class RouterListener |
| 9 | +{ |
| 10 | + private $router; |
| 11 | + |
| 12 | + private $routeBasePaths; |
| 13 | + |
| 14 | + private $domains; |
| 15 | + |
| 16 | + public function __construct(RouterInterface $router, array $routeBasePaths, array $domains) |
| 17 | + { |
| 18 | + $this->router = $router; |
| 19 | + $this->routeBasePaths = $routeBasePaths; |
| 20 | + $this->domains = $domains; |
| 21 | + } |
| 22 | + |
| 23 | + public function onGenerate(RouterGenerateEvent $event) |
| 24 | + { |
| 25 | + // If _locale parameter exists, use corresponding domain and force absolute URL |
| 26 | + if ($locale = $event->getParameters()['_locale'] ?? null) { |
| 27 | + $domain = $this->domains[$locale]; |
| 28 | + |
| 29 | + $event->setReferenceType(UrlGeneratorInterface::ABSOLUTE_URL); |
| 30 | + $this->updateRouterContext($domain); |
| 31 | + |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + // Else, search what is current route locale |
| 36 | + $route = $event->getRoute(); |
| 37 | + |
| 38 | + if (!is_string($route)) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + foreach ($this->routeBasePaths as $routeBasePath) { |
| 43 | + foreach ($this->domains as $locale => $domain) { |
| 44 | + if (0 === strpos($route, sprintf('%s/%s', $routeBasePath, $locale))) { |
| 45 | + $this->updateRouterContext($domain); |
| 46 | + $event->setParameter('_locale', $locale); |
| 47 | + |
| 48 | + return; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private function updateRouterContext(string $host): void |
| 55 | + { |
| 56 | + $this->router |
| 57 | + ->getContext() |
| 58 | + ->setHost($host) |
| 59 | + ; |
| 60 | + } |
| 61 | +} |
0 commit comments