add service_container to menuComposer instead of router to avoid circular references

This commit is contained in:
Julien Fastré 2014-10-12 21:00:16 +02:00
parent 9f31c3017d
commit 78a522d48f
2 changed files with 16 additions and 11 deletions

View File

@ -6,7 +6,7 @@ services:
class: CL\Chill\MainBundle\Routing\MenuComposer class: CL\Chill\MainBundle\Routing\MenuComposer
#must be set in function to avoid circular reference with chill.main.twig.chill_menu #must be set in function to avoid circular reference with chill.main.twig.chill_menu
calls: calls:
- [setRoute, ["@router"]] - [setContainer, ["@service_container"]]
chill.main.twig.chill_menu: chill.main.twig.chill_menu:
class: CL\Chill\MainBundle\Routing\MenuTwig class: CL\Chill\MainBundle\Routing\MenuTwig

View File

@ -4,6 +4,8 @@ namespace CL\Chill\MainBundle\Routing;
use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/** /**
* This class permit to build menu from the routing information * This class permit to build menu from the routing information
@ -13,25 +15,27 @@ use Symfony\Component\Routing\RouteCollection;
* *
* @author julien * @author julien
*/ */
class MenuComposer class MenuComposer implements ContainerAwareInterface
{ {
/** /**
* *
* @var \Symfony\Component\Routing\RouteCollection; * @var ContainerInterface
*/ */
private $routeCollection; private $container;
/** /**
* *
* @internal must be set in function instead of controller to avoid circular reference * @internal using the service router in container cause circular references
* with MenuTwig * @param ContainerInterface $container
* @param RouterInterface $router
*/ */
public function setRoute(RouterInterface $router) public function setContainer(ContainerInterface $container = null)
{ {
if (NULL === $container) {
throw new LogicException('container should not be null');
}
//see remark in MenuComposer::setRouteCollection //see remark in MenuComposer::setRouteCollection
$this->routeCollection = $router->getRouteCollection(); $this->container = $container;
} }
/** /**
@ -58,8 +62,9 @@ class MenuComposer
public function getRoutesFor($menuId, array $parameters = array()) public function getRoutesFor($menuId, array $parameters = array())
{ {
$routes = array(); $routes = array();
$routeCollection = $this->container->get('router')->getRouteCollection();
foreach ($this->routeCollection->all() as $routeKey => $route) { foreach ($routeCollection->all() as $routeKey => $route) {
if ($route->hasOption('menus')) { if ($route->hasOption('menus')) {
if (array_key_exists($menuId, $route->getOption('menus'))) { if (array_key_exists($menuId, $route->getOption('menus'))) {
$route = $route->getOption('menus')[$menuId]; $route = $route->getOption('menus')[$menuId];