<?php
namespace Boab\CmsBundle\Routing;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Cmf\Component\Routing\Event\Events;
use Symfony\Cmf\Component\Routing\Event\RouterGenerateEvent;
use Boab\CmsBundle\Routing\RouteParameterInterface;
class DynamicRouterGeneratorListener implements EventSubscriberInterface
{
private $router;
private $accessor;
private $routeCollection;
public function __construct(RouterInterface $router, PropertyAccessorInterface $accessor)
{
$this->router = $router;
$this->accessor = $accessor;
}
public function onRouteGenerate(RouterGenerateEvent $event)
{
$parameters = $event->getParameters();
if(is_array($parameters)){
return;
}
$parameters = $this->getRouteParameters($event->getRoute(), $parameters);
$event->setParameters($parameters);
}
private function getRouteParameters($routeName, $object)
{
if($object instanceof RouteParameterInterface){
$parameters = $object->getRouteParameters();
if(!is_array($parameters)){
throw new \InvalidArgumentException(sprintf('The return value of %s::%s must be an array %s given', get_class($object), 'getRouteParameters', gettype($parameters)));
}
return $parameters;
}
if(null === $this->routeCollection){
$this->routeCollection = $this->router->getRouteCollection();
}
$route = $this->routeCollection->get($routeName);
if(!$route){
return;
}
$parameters = [];
foreach ($route->compile()->getVariables() as $variable) {
if ($this->accessor->isReadable($object, $variable)) {
$parameters[$variable] = $this->accessor->getValue($object, $variable);
}
}
return $parameters;
}
public static function getSubscribedEvents():array
{
return [
Events::PRE_DYNAMIC_GENERATE => ['onRouteGenerate']
];
}
}