<?php
namespace WAM\Bundle\RoutingBundle\Routing;
use Doctrine\ORM\EntityRepository;
use Symfony\Cmf\Bundle\RoutingBundle\Routing\DynamicRouter;
use WAM\Bundle\RoutingBundle\Repository\Interfaces\RouteRepositoryInterface;
use WAM\Bundle\RoutingBundle\Repository\Interfaces\UrlRepositoryInterface;
class TranslatableDynamicRouter extends DynamicRouter
{
const LOCALE_PARAMETER = '_locale';
private RouteRepositoryInterface $routeRepository;
private UrlRepositoryInterface $urlRepository;
/**
* Setter for UrlRepository.
*
* @param EntityRepository $urlRepository
*
* @return $this
*/
public function setUrlRepository(UrlRepositoryInterface $urlRepository)
{
$this->urlRepository = $urlRepository;
return $this;
}
/**
* Setter for RouteRepository.
*
* @param RouteRepositoryInterface $routeRepository
*
* @return $this
*/
public function setRouteRepository(RouteRepositoryInterface $routeRepository)
{
$this->routeRepository = $routeRepository;
return $this;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = [], $absolute = false)
{
if (is_string($name)) {
$locale = isset($parameters[self::LOCALE_PARAMETER]) ?
$parameters[self::LOCALE_PARAMETER] :
$this->getRequest()->getLocale();
$route = $this->findRoute($name, $locale) ?: $this->findUrl($name);
return $route ?
parent::generate($route, $parameters, $absolute) :
null;
}
return;
}
private function findRoute($name, $locale)
{
$candidates = $this->routeRepository->findPrimaryByCanonicalName($name);
foreach ($candidates as $route) {
if ($this->checkLocaleRequirement($route, $locale)) {
return $route;
}
}
return;
}
private function findUrl($name)
{
return $this->urlRepository->getByName($name);
}
private function checkLocaleRequirement($route, $locale)
{
return empty($locale)
|| !$route->getRequirement(self::LOCALE_PARAMETER)
|| preg_match('/' . $route->getRequirement(self::LOCALE_PARAMETER) . '/', $locale);
}
}