lib/boab/cms-bundle/src/Routing/DynamicRouterGeneratorListener.php line 23

Open in your IDE?
  1. <?php 
  2. namespace Boab\CmsBundle\Routing;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  5. use Symfony\Component\Routing\RouterInterface;
  6. use Symfony\Cmf\Component\Routing\Event\Events;
  7. use Symfony\Cmf\Component\Routing\Event\RouterGenerateEvent;
  8. use Boab\CmsBundle\Routing\RouteParameterInterface;
  9. class DynamicRouterGeneratorListener implements EventSubscriberInterface
  10. {
  11.     private $router;
  12.     private $accessor;
  13.     private $routeCollection;
  14.     public function __construct(RouterInterface $routerPropertyAccessorInterface $accessor)
  15.     {
  16.         $this->router $router;
  17.         $this->accessor $accessor;
  18.     }
  19.     
  20.     public function onRouteGenerate(RouterGenerateEvent $event)
  21.     {
  22.         $parameters $event->getParameters();
  23.         if(is_array($parameters)){
  24.             return;
  25.         }
  26.         $parameters $this->getRouteParameters($event->getRoute(), $parameters);
  27.         
  28.         $event->setParameters($parameters);
  29.     }
  30.     private function getRouteParameters($routeName$object)
  31.     {
  32.         if($object instanceof RouteParameterInterface){
  33.             $parameters $object->getRouteParameters();
  34.             if(!is_array($parameters)){
  35.                 throw new \InvalidArgumentException(sprintf('The return value of %s::%s must be an array %s given'get_class($object), 'getRouteParameters'gettype($parameters)));
  36.             }
  37.             return $parameters;
  38.         }
  39.         if(null === $this->routeCollection){
  40.             $this->routeCollection $this->router->getRouteCollection();
  41.         }
  42.         $route $this->routeCollection->get($routeName);
  43.         if(!$route){
  44.             return;
  45.         }
  46.         $parameters = [];
  47.         foreach ($route->compile()->getVariables() as $variable) {
  48.             if ($this->accessor->isReadable($object$variable)) {
  49.                 $parameters[$variable] = $this->accessor->getValue($object$variable);
  50.             }
  51.         }  
  52.         return $parameters
  53.     }
  54.         
  55.     public static function getSubscribedEvents():array
  56.     {
  57.         return [
  58.            Events::PRE_DYNAMIC_GENERATE => ['onRouteGenerate']
  59.         ];
  60.     }    
  61. }