Bladeren bron

Refactored creation of sidebar menu by using menu builder

Martin Hasoň 10 jaren geleden
bovenliggende
commit
3f6874faa3

+ 10 - 0
DependencyInjection/SonataAdminExtension.php

@@ -72,6 +72,16 @@ BOOM
         $loader->load('validator.xml');
         $loader->load('route.xml');
         $loader->load('block.xml');
+        $loader->load('menu.xml');
+
+        // TODO: Go back on xml configuration when bumping requirements to SF 2.6+
+        $sidebarMenu = $container->getDefinition('sonata.admin.sidebar_menu');
+        if (method_exists($sidebarMenu, 'setFactory')) {
+            $sidebarMenu->setFactory(array(new Reference('sonata.admin.menu_builder'), 'createSidebarMenu'));
+        } else {
+            $sidebarMenu->setFactoryService('sonata.admin.menu_builder');
+            $sidebarMenu->setFactoryMethod('createSidebarMenu');
+        }
 
         $configuration = new Configuration();
         $processor = new Processor();

+ 135 - 0
Menu/MenuBuilder.php

@@ -0,0 +1,135 @@
+<?php
+/*
+ * This file is part of the Sonata package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ *
+ */
+
+namespace Sonata\AdminBundle\Menu;
+
+use Knp\Menu\FactoryInterface;
+use Knp\Menu\ItemInterface;
+use Knp\Menu\Provider\MenuProviderInterface;
+use Sonata\AdminBundle\Admin\Pool;
+use Symfony\Component\HttpFoundation\Request;
+
+/**
+ * Sonata menu builder.
+ *
+ * @author Martin Hasoň <martin.hason@gmail.com>
+ */
+class MenuBuilder
+{
+    private $pool;
+    private $factory;
+    private $provider;
+    private $request;
+
+    /**
+     * Constructor.
+     *
+     * @param Pool                  $pool
+     * @param FactoryInterface      $factory
+     * @param MenuProviderInterface $provider
+     */
+    public function __construct(Pool $pool, FactoryInterface $factory, MenuProviderInterface $provider)
+    {
+        $this->pool = $pool;
+        $this->factory = $factory;
+        $this->provider = $provider;
+    }
+
+    /**
+     * Builds sidebar menu.
+     *
+     * @return ItemInterface
+     */
+    public function createSidebarMenu()
+    {
+        $menu = $this->factory->createItem('root', array(
+            'extras' => array(
+                'request' => $this->request,
+            ),
+        ));
+
+        foreach ($this->pool->getAdminGroups() as $name => $group) {
+            $attributes = array(
+                'icon' => $group['icon'],
+                'label_catalogue' => $group['label_catalogue'],
+            );
+
+            $extras = array(
+                'roles' => $group['roles'],
+            );
+
+            // Check if the menu group is built by a menu provider
+            if (isset($group['provider'])) {
+                $subMenu = $this->provider->get($group['provider']);
+
+                $menu
+                    ->addChild($subMenu)
+                    ->setExtras(array_merge($subMenu->getExtras(), $extras))
+                    ->setAttributes(array_merge($subMenu->getAttributes(), $attributes))
+                ;
+
+                continue;
+            }
+
+            // The menu group is built by config
+            $menu->addChild($name, array(
+                'label' => $group['label'],
+                'attributes' => $attributes,
+                'extras' => $extras,
+            ));
+
+            foreach ($group['items'] as $item) {
+                if (isset($item['admin']) && !empty($item['admin'])) {
+                    $admin = $this->pool->getInstance($item['admin']);
+
+                    // skip menu item if no `list` url is available or user doesn't have the LIST access rights
+                    if (!$admin->hasRoute('list') || !$admin->isGranted('LIST')) {
+                        continue;
+                    }
+
+                    $label = $admin->getLabel();
+                    $options = $admin->generateMenuUrl('list');
+                    $options['extras'] = array(
+                        'translation_domain' =>$admin->getTranslationDomain(),
+                        'admin' => $admin,
+                    );
+                } else {
+                    $label = $item['label'];
+                    $options = array(
+                        'route' => $item['route'],
+                        'routeParameters' => $item['route_params'],
+                        'extras' => array(
+                            'translation_domain' => $group['label_catalogue'],
+                        )
+                    );
+                }
+
+                $menu[$name]->addChild($label, $options);
+            }
+
+            if (0 === count($menu[$name]->getChildren())) {
+                $menu->removeChild($name);
+            }
+        }
+
+        return $menu;
+    }
+
+    /**
+     * Sets the request the service
+     *
+     * @param Request $request
+     */
+    public function setRequest(Request $request = null)
+    {
+        $this->request = $request;
+    }
+}

+ 19 - 0
Resources/config/menu.xml

@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<container xmlns="http://symfony.com/schema/dic/services"
+           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
+
+    <services>
+        <service id="sonata.admin.menu_builder" class="Sonata\AdminBundle\Menu\MenuBuilder">
+            <argument type="service" id="sonata.admin.pool" />
+            <argument type="service" id="knp_menu.factory" />
+            <argument type="service" id="knp_menu.menu_provider" />
+            <call method="setRequest"><argument type="service" id="request" on-invalid="null" strict="false" /></call>
+        </service>
+
+        <service id="sonata.admin.sidebar_menu" class="Knp\Menu\MenuItem">
+            <tag name="knp_menu.menu" alias="sonata_admin_sidebar" />
+        </service>
+    </services>
+</container>

+ 0 - 2
Resources/config/twig.xml

@@ -9,8 +9,6 @@
             <tag name="twig.extension"/>
 
             <argument type="service" id="sonata.admin.pool" />
-            <argument type="service" id="router" />
-            <argument type="service" id="knp_menu.helper" />
             <argument type="service" id="logger" on-invalid="ignore" />
         </service>
     </services>

+ 5 - 5
Resources/doc/cookbook/recipe_knp_menu.rst

@@ -13,7 +13,7 @@ Create your controller:
 
 .. code-block:: php
 
-    class BlogController 
+    class BlogController
     {
         /**
          * @Route("/blog", name="blog_home")
@@ -68,9 +68,9 @@ And voilà, now you have a menu group which contains a link to a sonata admin vi
 Using a menu provider
 ---------------------
 
-As seen above, the main way to declare your menu is by declaring items in your sonata admin config file. In some case you may have to create a more complexe menu depending on your business logic. This is possible by using a menu provider to populate a whole menu group. This is done with the ``provider`` config value.
+As seen above, the main way to declare your menu is by declaring items in your sonata admin config file. In some case you may have to create a more complex menu depending on your business logic. This is possible by using a menu provider to populate a whole menu group. This is done with the ``provider`` config value.
 
-Tthe following configuration uses a menu provider to populate the menu group ``my_group``:
+The following configuration uses a menu provider to populate the menu group ``my_group``:
 
 .. code-block:: yaml
 
@@ -81,7 +81,7 @@ Tthe following configuration uses a menu provider to populate the menu group ``m
                     provider:        'MyBundle:MyMenuProvider:getMyMenu'
                     icon:            '<i class="fa fa-edit"></i>'
 
-With KnpMenuBundle you can create a custom menu by using a builder class or by declaring it as a service. Please see the `Knp documentation <http://symfony.com/doc/current/bundles/KnpMenuBundle/index.html#create-your-first-menu>`_ for further information. 
+With KnpMenuBundle you can create a custom menu by using a builder class or by declaring it as a service. Please see the `Knp documentation <http://symfony.com/doc/current/bundles/KnpMenuBundle/index.html#create-your-first-menu>`_ for further information.
 
 In sonata, whatever the implementation you choose, you only have to provide the menu alias to the provider config key:
 
@@ -93,4 +93,4 @@ In sonata, whatever the implementation you choose, you only have to provide the
             <tag name="knp_menu.menu" alias="my_menu_alias" />
         </service>
 
-Please note that when using the provider option, you can't set the menu label via the configuration. It is done in your custom menu.
+Please note that when using the provider option, you can't set the menu label via the configuration. It is done in your custom menu.

+ 2 - 2
Resources/doc/cookbook/recipe_overwrite_admin_configuration.rst

@@ -21,7 +21,7 @@ From the configuration file, you can add a new section named ``admin_services``
                 route_generator:            sonata.admin.route.default_generator
                 validator:                  validator
                 security_handler:           sonata.admin.security.handler
-                menu_factor:                knp_menu.factory
+                menu_factory:               knp_menu.factory
                 route_builder:              sonata.admin.route.path_info
                 label_translator_strategy:  sonata.admin.label.strategy.native
 
@@ -35,4 +35,4 @@ From the configuration file, you can add a new section named ``admin_services``
                     filter: [ 'MyTheme.twig.html', 'MySecondTheme.twig.html']
 
 
-With these settings you will be able to change default services and templates used by the `id.of.admin.service`` admin instance.
+With these settings you will be able to change default services and templates used by the `id.of.admin.service`` admin instance.

+ 10 - 12
Resources/views/Menu/sonata_menu.html.twig

@@ -2,30 +2,30 @@
 
 {% block root %}
     {%- set listAttributes = item.childrenAttributes|merge({'class': 'sidebar-menu'}) %}
-    {%- set request        = item.getExtra('request') %}
+    {%- set request        = item.extra('request') %}
     {{ block('list') -}}
 {% endblock %}
 
 {% block item %}
     {%- if item.displayed %}
         {#- check role of the group #}
-        {%- set display = (item.getExtra('roles') is empty or is_granted('ROLE_SUPER_ADMIN') ) %}
-        {%- for role in item.getExtra('roles') if not display %}
+        {%- set display = (item.extra('roles') is empty or is_granted('ROLE_SUPER_ADMIN') ) %}
+        {%- for role in item.extra('roles') if not display %}
             {%- set display = is_granted(role) %}
         {%- endfor %}
     {%- endif %}
 
     {%- if item.displayed and display|default %}
         {%- set active = false %}
-        {%- if item.getExtra('active') is not empty and item.getExtra('active') %}
+        {%- if item.extra('active') is not empty and item.extra('active') %}
             {%- set active = true %}
-        {%- elseif item.getExtra('admin') is not empty and item.getExtra('admin').hasroute('list') and item.getExtra('admin').isGranted('LIST') and request.get('_sonata_admin') == item.getExtra('admin').code %}
+        {%- elseif item.extra('admin') is not empty and item.extra('admin').hasroute('list') and item.extra('admin').isGranted('LIST') and request.get('_sonata_admin') == item.extra('admin').code %}
             {%- set active = true %}
         {%- elseif item.route is defined and request.get('_route') == item.route %}
             {%- set active = true %}
         {%- else %}
             {%- for child in item.children if not active %}
-                {%- if child.getExtra('admin') is not empty and child.getExtra('admin').hasroute('list') and child.getExtra('admin').isGranted('LIST') and request.get('_sonata_admin') == child.getExtra('admin').code %}
+                {%- if child.extra('admin') is not empty and child.extra('admin').hasroute('list') and child.extra('admin').isGranted('LIST') and request.get('_sonata_admin') == child.extra('admin').code %}
                     {%- set active = true %}
                 {%-  elseif child.route is defined and request.get('_route') == child.route %}
                     {%- set active = true %}
@@ -48,8 +48,8 @@
 
 {% block linkElement %}
     {% spaceless %}
-        {% set translation_domain = item.getExtra('translationdomain', 'messages') %}
-        {% set icon = item.attribute('icon') ? item.attribute('icon') : (item.level > 1 ? '<i class="fa fa-angle-double-right"></i>' : '') %}
+        {% set translation_domain = item.extra('translation_domain', 'messages') %}
+        {% set icon = item.attribute('icon')|default(item.level > 1 ? '<i class="fa fa-angle-double-right"></i>' : '') %}
         {% set is_link = true %}
         {{ parent() }}
     {% endspaceless %}
@@ -57,15 +57,13 @@
 
 {% block spanElement %}
     {% spaceless %}
-
         <a href="#">
             {% set translation_domain = item.attribute('label_catalogue') %}
-            {% set icon = item.attribute('icon')|default ? item.attribute('icon') : '' %}
-            {{ icon|default|raw }}
+            {% set icon = item.attribute('icon')|default('') %}
             {{ parent() }}
             <i class="fa pull-right fa-angle-left"></i>
         </a>
     {% endspaceless %}
 {% endblock %}
 
-{% block label %}{% if is_link is defined and is_link %}{{ icon|default|raw }}{% endif %}{% if options.allow_safe_labels and item.getExtra('safe_label', false) %}{{ item.label|raw }}{% else %}{{ item.label|trans({}, translation_domain|default('messages')) }}{% endif %}{% endblock %}
+{% block label %}{% if is_link is defined and is_link %}{{ icon|default|raw }}{% endif %}{% if options.allow_safe_labels and item.extra('safe_label', false) %}{{ item.label|raw }}{% else %}{{ item.label|trans({}, translation_domain|default('messages')) }}{% endif %}{% endblock %}

+ 1 - 1
Resources/views/standard_layout.html.twig

@@ -216,7 +216,7 @@ file that was distributed with this source code.
                             {% block side_bar_before_nav %} {% endblock %}
                             {% block side_bar_nav %}
                                 {% if app.security.token and is_granted('ROLE_SONATA_ADMIN') %}
-                                    {{ knp_menu_render(sonata_knp_menu_build(app.request), {'template' : admin_pool.getTemplate('knp_menu_template')}) }}
+                                    {{ knp_menu_render('sonata_admin_sidebar', {template: admin_pool.getTemplate('knp_menu_template')}) }}
                                 {% endif %}
                             {% endblock side_bar_nav %}
                             {% block side_bar_after_nav %}

+ 2 - 2
Tests/DependencyInjection/Compiler/AddDependencyCallsCompilerPassTest.php

@@ -394,8 +394,8 @@ class AddDependencyCallsCompilerPassTest extends \PHPUnit_Framework_TestCase
             ->register('knp_menu.factory')
             ->setClass('Knp\Menu\Silex\RouterAwareFactory');
         $container
-            ->register('knp_menu.helper')
-            ->setClass('Knp\Menu\Twig\Helper');
+            ->register('knp_menu.menu_provider')
+            ->setClass('Knp\Menu\Provider\MenuProviderInterface');
         $container
             ->register('event_dispatcher')
             ->setClass('Symfony\Component\EventDispatcher\EventDispatcherInterface');

+ 5 - 2
Tests/DependencyInjection/Compiler/ExtensionCompilerPassTest.php

@@ -356,8 +356,11 @@ class ExtensionCompilerPassTest extends \PHPUnit_Framework_TestCase
             ->register('validator')
             ->setClass('Symfony\Component\Validator\ValidatorInterface');
         $container
-            ->register('knp_menu.helper')
-            ->setClass('Knp\Menu\Twig\Helper');
+            ->register('knp_menu.factory')
+            ->setClass('Knp\Menu\FactoryInterface');
+        $container
+            ->register('knp_menu.menu_provider')
+            ->setClass('Knp\Menu\Provider\MenuProviderInterface');
 
         // Add admin definition's
         $container

+ 261 - 0
Tests/Menu/MenuBuilderTest.php

@@ -0,0 +1,261 @@
+<?php
+
+/*
+ * This file is part of the Sonata package.
+ *
+ * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Sonata\AdminBundle\Tests\Twig\Extension;
+
+use Knp\Menu\MenuFactory;
+use Sonata\AdminBundle\Menu\MenuBuilder;
+
+class MenuBuilderTest extends \PHPUnit_Framework_TestCase
+{
+    private $pool;
+    private $provider;
+    private $factory;
+    private $builder;
+
+    protected function setUp()
+    {
+        $this->pool = $this->getMockBuilder('Sonata\AdminBundle\Admin\Pool')->disableOriginalConstructor()->getMock();
+        $this->provider = $this->getMock('Knp\Menu\Provider\MenuProviderInterface');
+        $this->factory = new MenuFactory();
+
+        $this->builder = new MenuBuilder($this->pool, $this->factory, $this->provider);
+    }
+
+    public function testGetKnpMenu()
+    {
+        $adminGroups = array(
+            "bar" => array(
+                "label" => "foo",
+                "icon"  => '<i class="fa fa-edit"></i>',
+                "label_catalogue"  => 'SonataAdminBundle',
+                "items" => array(
+                    array(
+                        "admin"        => "",
+                        "label"        => "fooLabel",
+                        "route"        => "FooRoute",
+                        "route_params" => array("foo" => "bar"),
+                    ),
+                ),
+                "item_adds" => array(),
+                "roles"     => array(),
+
+            ),
+        );
+
+        $this->preparePool($adminGroups);
+
+        $menu = $this->builder->createSidebarMenu();
+
+        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
+        $this->assertArrayHasKey('bar', $menu->getChildren());
+
+        foreach ($menu->getChildren() as $key => $child) {
+            $this->assertInstanceOf('Knp\Menu\MenuItem', $child);
+            $this->assertEquals("bar", $child->getName());
+            $this->assertEquals($adminGroups["bar"]["label"], $child->getLabel());
+
+            // menu items
+            $children = $child->getChildren();
+            $this->assertCount(1, $children);
+            $this->assertArrayHasKey('fooLabel', $children);
+            $this->assertInstanceOf('Knp\Menu\MenuItem', $child['fooLabel']);
+            $this->assertEquals('fooLabel', $child['fooLabel']->getLabel());
+        }
+    }
+
+    public function testGetKnpMenuWithAdmin()
+    {
+        $adminGroups = array(
+            'bar' => array(
+                'label' => 'foo',
+                'icon'  => '<i class="fa fa-edit"></i>',
+                'label_catalogue'  => 'SonataAdminBundle',
+                'items' => array(
+                    array(
+                        'admin'        => 'sonata_admin_foo_service',
+                        'label'        => 'fooLabel',
+                    ),
+                ),
+                'item_adds' => array(),
+                'roles'     => array(),
+            ),
+        );
+
+        $admin = $this->getMock('Sonata\AdminBundle\Admin\AdminInterface');
+        $admin->expects($this->once())
+            ->method('hasRoute')
+            ->with($this->equalTo('list'))
+            ->will($this->returnValue(true))
+        ;
+
+        $admin->expects($this->any())
+            ->method('isGranted')
+            ->with($this->equalTo('LIST'))
+            ->will($this->returnValue(true))
+        ;
+
+        $admin->expects($this->once())
+            ->method('getLabel')
+            ->will($this->returnValue('foo_admin_label'))
+        ;
+
+        $admin->expects($this->once())
+            ->method('generateMenuUrl')
+            ->will($this->returnValue(array()))
+        ;
+
+        $this->preparePool($adminGroups, $admin);
+        $menu = $this->builder->createSidebarMenu();
+
+        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
+        $this->assertArrayHasKey('bar', $menu->getChildren());
+
+        foreach ($menu->getChildren() as $key => $child) {
+            $this->assertInstanceOf('Knp\Menu\MenuItem', $child);
+            $this->assertEquals('bar', $child->getName());
+            $this->assertEquals($adminGroups['bar']['label'], $child->getLabel());
+
+            // menu items
+            $children = $child->getChildren();
+            $this->assertCount(1, $children);
+            $this->assertArrayHasKey('foo_admin_label', $children);
+            $this->assertInstanceOf('Knp\Menu\MenuItem', $child['foo_admin_label']);
+            $this->assertEquals('foo_admin_label', $child['foo_admin_label']->getLabel());
+        }
+    }
+
+    public function testGetKnpMenuWithNoListRoute()
+    {
+        $adminGroups = array(
+            'bar' => array(
+                'label' => 'foo',
+                'icon'  => '<i class="fa fa-edit"></i>',
+                'label_catalogue'  => 'SonataAdminBundle',
+                'items' => array(
+                    array(
+                        'admin'        => 'sonata_admin_foo_service',
+                        'label'        => 'fooLabel',
+                    ),
+                ),
+                'item_adds' => array(),
+                'roles'     => array(),
+            ),
+        );
+
+        $admin = $this->getMock('Sonata\AdminBundle\Admin\AdminInterface');
+        $admin->expects($this->once())
+            ->method('hasRoute')
+            ->with($this->equalTo('list'))
+            ->will($this->returnValue(false))
+        ;
+
+        $this->preparePool($adminGroups, $admin);
+        $menu = $this->builder->createSidebarMenu();
+
+        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
+        $this->assertArrayNotHasKey('bar', $menu->getChildren());
+        $this->assertCount(0, $menu->getChildren());
+    }
+
+    public function testGetKnpMenuWithNotGrantedList()
+    {
+        $adminGroups = array(
+            'bar' => array(
+                'label' => 'foo',
+                'icon'  => '<i class="fa fa-edit"></i>',
+                'label_catalogue'  => 'SonataAdminBundle',
+                'items' => array(
+                    array(
+                        'admin'        => 'sonata_admin_foo_service',
+                        'label'        => 'fooLabel',
+                    ),
+                ),
+                'item_adds' => array(),
+                'roles'     => array(),
+            ),
+        );
+
+        $admin = $this->getMock('Sonata\AdminBundle\Admin\AdminInterface');
+        $admin->expects($this->once())
+            ->method('hasRoute')
+            ->with($this->equalTo('list'))
+            ->will($this->returnValue(true))
+        ;
+
+        $admin->expects($this->any())
+            ->method('isGranted')
+            ->with($this->equalTo('LIST'))
+            ->will($this->returnValue(false))
+        ;
+
+        $this->preparePool($adminGroups, $admin);
+        $menu = $this->builder->createSidebarMenu();
+
+        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
+        $this->assertArrayNotHasKey('bar', $menu->getChildren());
+        $this->assertCount(0, $menu->getChildren());
+    }
+
+    public function testGetKnpMenuWithProvider()
+    {
+        $adminGroups = array(
+            "bar" => array(
+                "provider"        => 'my_menu',
+                "label_catalogue" => '',
+                "icon"            => '<i class="fa fa-edit"></i>',
+                "roles"           => array(),
+            ),
+        );
+
+        $this->provider
+            ->expects($this->once())
+            ->method('get')
+            ->with('my_menu')
+            ->will($this->returnValue($this->factory->createItem('bar')->addChild('foo')->getParent()))
+        ;
+
+        $this->preparePool($adminGroups);
+        $menu = $this->builder->createSidebarMenu();
+
+        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
+        $this->assertArrayHasKey('bar', $menu->getChildren());
+
+        foreach ($menu->getChildren() as $key => $child) {
+            $this->assertInstanceOf('Knp\Menu\MenuItem', $child);
+            $this->assertEquals("bar", $child->getName());
+            $this->assertEquals("bar", $child->getLabel());
+
+            // menu items
+            $children = $child->getChildren();
+            $this->assertCount(1, $children);
+            $this->assertArrayHasKey('foo', $children);
+            $this->assertInstanceOf('Knp\Menu\MenuItem', $child['foo']);
+            $this->assertEquals('foo', $child['foo']->getLabel());
+        }
+    }
+
+    private function preparePool($adminGroups, $admin = null)
+    {
+        $this->pool->expects($this->once())
+            ->method('getAdminGroups')
+            ->will($this->returnValue($adminGroups))
+        ;
+
+        if (null !== $admin) {
+            $this->pool->expects($this->once())
+                ->method('getInstance')
+                ->with($this->equalTo('sonata_admin_foo_service'))
+                ->will($this->returnValue($admin))
+            ;
+        }
+    }
+}

+ 1 - 218
Tests/Twig/Extension/SonataAdminExtensionTest.php

@@ -11,8 +11,6 @@
 
 namespace Sonata\AdminBundle\Tests\Twig\Extension;
 
-use Knp\Menu\MenuFactory;
-use Knp\Menu\MenuItem;
 use Sonata\AdminBundle\Admin\Pool;
 use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
 use Sonata\AdminBundle\Admin\AdminInterface;
@@ -25,7 +23,6 @@ use Symfony\Component\Config\FileLocator;
 use Symfony\Component\Routing\Generator\UrlGenerator;
 use Symfony\Component\Routing\Loader\XmlFileLoader;
 use Symfony\Component\Routing\RequestContext;
-use Symfony\Component\Routing\RouterInterface;
 use Symfony\Component\Translation\Translator;
 use Symfony\Component\Translation\MessageSelector;
 use Symfony\Component\Translation\Loader\XliffFileLoader;
@@ -73,11 +70,6 @@ class SonataAdminExtensionTest extends \PHPUnit_Framework_TestCase
      */
     private $pool;
 
-    /**
-     * @var Router
-     */
-    private $router;
-
     /**
      * @var LoggerInterface
      */
@@ -93,19 +85,9 @@ class SonataAdminExtensionTest extends \PHPUnit_Framework_TestCase
         $this->pool->setAdminServiceIds(array('sonata_admin_foo_service'));
         $this->pool->setAdminClasses(array('fooClass' => array('sonata_admin_foo_service')));
 
-        $this->router = $this->getMock('Symfony\Component\Routing\RouterInterface');
-
         $this->logger = $this->getMock('Psr\Log\LoggerInterface');
 
-        $menu = new MenuItem('bar', new MenuFactory());
-        $menu->addChild('foo');
-        $this->helper = $this->getMockBuilder('Knp\Menu\Twig\Helper')->disableOriginalConstructor()->getMock();
-        $this->helper->expects($this->any())
-            ->method('get')
-            ->with('my_menu')
-            ->willReturn($menu);
-
-        $this->twigExtension = new SonataAdminExtension($this->pool, $this->router, $this->helper, $this->logger);
+        $this->twigExtension = new SonataAdminExtension($this->pool, $this->logger);
 
         $loader = new StubFilesystemLoader(array(
             __DIR__.'/../../../Resources/views/CRUD',
@@ -882,203 +864,4 @@ class SonataAdminExtensionTest extends \PHPUnit_Framework_TestCase
 
         $this->assertEquals(1234567, $this->twigExtension->getUrlsafeIdentifier($entity, $this->adminBar));
     }
-
-    public function testGetKnpMenu()
-    {
-        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
-
-        $adminGroups = array(
-            "bar" => array(
-                "label" => "foo",
-                "icon"  => '<i class="fa fa-edit"></i>',
-                "label_catalogue"  => 'SonataAdminBundle',
-                "items" => array(
-                    array(
-                        "admin"        => "",
-                        "label"        => "fooLabel",
-                        "route"        => "FooRoute",
-                        "route_params" => array("foo" => "bar"),
-                    ),
-                ),
-                "item_adds" => array(),
-                "roles"     => array(),
-
-            ),
-        );
-        $this->pool->setAdminGroups($adminGroups);
-        $menu = $this->twigExtension->getKnpMenu($request);
-
-        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
-        $this->assertArrayHasKey('bar', $menu->getChildren());
-
-        foreach ($menu->getChildren() as $key => $child) {
-            $this->assertInstanceOf('Knp\Menu\MenuItem', $child);
-            $this->assertEquals("bar", $child->getName());
-            $this->assertEquals($adminGroups["bar"]["label"], $child->getLabel());
-
-            // menu items
-            $children = $child->getChildren();
-            $this->assertCount(1, $children);
-            $this->assertArrayHasKey('fooLabel', $children);
-            $this->assertInstanceOf('Knp\Menu\MenuItem', $child['fooLabel']);
-            $this->assertEquals('fooLabel', $child['fooLabel']->getLabel());
-        }
-    }
-
-    public function testGetKnpMenuWithAdmin()
-    {
-        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
-
-        $adminGroups = array(
-            'bar' => array(
-                'label' => 'foo',
-                'icon'  => '<i class="fa fa-edit"></i>',
-                'label_catalogue'  => 'SonataAdminBundle',
-                'items' => array(
-                    array(
-                        'admin'        => 'sonata_admin_foo_service',
-                        'label'        => 'fooLabel',
-                    ),
-                ),
-                'item_adds' => array(),
-                'roles'     => array(),
-            ),
-        );
-        $this->pool->setAdminGroups($adminGroups);
-
-        $this->admin->expects($this->once())
-            ->method('hasRoute')
-            ->with($this->equalTo('list'))
-            ->will($this->returnValue(true));
-
-        $this->admin->expects($this->any())
-            ->method('isGranted')
-            ->with($this->equalTo('LIST'))
-            ->will($this->returnValue(true));
-
-        $this->admin->expects($this->once())
-            ->method('getLabel')
-            ->will($this->returnValue('foo_admin_label'));
-
-        $menu = $this->twigExtension->getKnpMenu($request);
-
-        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
-        $this->assertArrayHasKey('bar', $menu->getChildren());
-
-        foreach ($menu->getChildren() as $key => $child) {
-            $this->assertInstanceOf('Knp\Menu\MenuItem', $child);
-            $this->assertEquals('bar', $child->getName());
-            $this->assertEquals($adminGroups['bar']['label'], $child->getLabel());
-
-            // menu items
-            $children = $child->getChildren();
-            $this->assertCount(1, $children);
-            $this->assertArrayHasKey('foo_admin_label', $children);
-            $this->assertInstanceOf('Knp\Menu\MenuItem', $child['foo_admin_label']);
-            $this->assertEquals('foo_admin_label', $child['foo_admin_label']->getLabel());
-        }
-    }
-
-    public function testGetKnpMenuWithNoListRoute()
-    {
-        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
-
-        $adminGroups = array(
-            'bar' => array(
-                'label' => 'foo',
-                'icon'  => '<i class="fa fa-edit"></i>',
-                'label_catalogue'  => 'SonataAdminBundle',
-                'items' => array(
-                    array(
-                        'admin'        => 'sonata_admin_foo_service',
-                        'label'        => 'fooLabel',
-                    ),
-                ),
-                'item_adds' => array(),
-                'roles'     => array(),
-            ),
-        );
-        $this->pool->setAdminGroups($adminGroups);
-
-        $this->admin->expects($this->once())
-            ->method('hasRoute')
-            ->with($this->equalTo('list'))
-            ->will($this->returnValue(false));
-
-        $menu = $this->twigExtension->getKnpMenu($request);
-
-        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
-        $this->assertArrayNotHasKey('bar', $menu->getChildren());
-        $this->assertCount(0, $menu->getChildren());
-    }
-
-    public function testGetKnpMenuWithNotGrantedList()
-    {
-        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
-
-        $adminGroups = array(
-            'bar' => array(
-                'label' => 'foo',
-                'icon'  => '<i class="fa fa-edit"></i>',
-                'label_catalogue'  => 'SonataAdminBundle',
-                'items' => array(
-                    array(
-                        'admin'        => 'sonata_admin_foo_service',
-                        'label'        => 'fooLabel',
-                    ),
-                ),
-                'item_adds' => array(),
-                'roles'     => array(),
-            ),
-        );
-        $this->pool->setAdminGroups($adminGroups);
-
-        $this->admin->expects($this->once())
-            ->method('hasRoute')
-            ->with($this->equalTo('list'))
-            ->will($this->returnValue(true));
-
-        $this->admin->expects($this->any())
-            ->method('isGranted')
-            ->with($this->equalTo('LIST'))
-            ->will($this->returnValue(false));
-
-        $menu = $this->twigExtension->getKnpMenu($request);
-
-        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
-        $this->assertArrayNotHasKey('bar', $menu->getChildren());
-        $this->assertCount(0, $menu->getChildren());
-    }
-
-    public function testGetKnpMenuWithProvider()
-    {
-        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
-
-        $adminGroups = array(
-            "bar" => array(
-                "provider"        => 'my_menu',
-                "label_catalogue" => '',
-                "icon"            => '<i class="fa fa-edit"></i>',
-                "roles"           => array(),
-            ),
-        );
-        $this->pool->setAdminGroups($adminGroups);
-        $menu = $this->twigExtension->getKnpMenu($request);
-
-        $this->assertInstanceOf('Knp\Menu\ItemInterface', $menu);
-        $this->assertArrayHasKey('bar', $menu->getChildren());
-
-        foreach ($menu->getChildren() as $key => $child) {
-            $this->assertInstanceOf('Knp\Menu\MenuItem', $child);
-            $this->assertEquals("bar", $child->getName());
-            $this->assertEquals("bar", $child->getLabel());
-
-            // menu items
-            $children = $child->getChildren();
-            $this->assertCount(1, $children);
-            $this->assertArrayHasKey('foo', $children);
-            $this->assertInstanceOf('Knp\Menu\MenuItem', $child['foo']);
-            $this->assertEquals('foo', $child['foo']->getLabel());
-        }
-    }
 }

+ 2 - 100
Twig/Extension/SonataAdminExtension.php

@@ -12,17 +12,12 @@
 namespace Sonata\AdminBundle\Twig\Extension;
 
 use Doctrine\Common\Util\ClassUtils;
-use Knp\Menu\MenuFactory;
-use Knp\Menu\ItemInterface;
-use Knp\Menu\Twig\Helper;
 use Psr\Log\LoggerInterface;
 use Sonata\AdminBundle\Admin\AdminInterface;
 use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
 use Sonata\AdminBundle\Admin\Pool;
 use Sonata\AdminBundle\Exception\NoValueException;
-use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\PropertyAccess\PropertyAccess;
-use Symfony\Component\Routing\RouterInterface;
 
 /**
  * Class SonataAdminExtension
@@ -42,16 +37,6 @@ class SonataAdminExtension extends \Twig_Extension
      */
     protected $pool;
 
-    /**
-     * @var RouterInterface
-     */
-    protected $router;
-
-    /**
-     * @var Helper
-     */
-    protected $knpHelper;
-
     /**
      * @var LoggerInterface
      */
@@ -59,16 +44,12 @@ class SonataAdminExtension extends \Twig_Extension
 
     /**
      * @param Pool            $pool
-     * @param RouterInterface $router
-     * @param Helper          $knpHelper
      * @param LoggerInterface $logger
      */
-    public function __construct(Pool $pool, RouterInterface $router, Helper $knpHelper, LoggerInterface $logger = null)
+    public function __construct(Pool $pool, LoggerInterface $logger = null)
     {
         $this->pool      = $pool;
         $this->logger    = $logger;
-        $this->router    = $router;
-        $this->knpHelper = $knpHelper;
     }
 
     /**
@@ -99,9 +80,7 @@ class SonataAdminExtension extends \Twig_Extension
      */
     public function getFunctions()
     {
-        return array(
-            'sonata_knp_menu_build' => new \Twig_Function_Method($this, 'getKnpMenu'),
-        );
+        return array();
     }
 
     /**
@@ -377,81 +356,4 @@ class SonataAdminExtension extends \Twig_Extension
 
         return isset($mapping[$type]) ? $mapping[$type] : false;
     }
-
-    /**
-     * Get KnpMenu
-     *
-     * @param Request $request
-     *
-     * @return ItemInterface
-     */
-    public function getKnpMenu(Request $request = null)
-    {
-        $menuFactory = new MenuFactory();
-        $menu = $menuFactory
-            ->createItem('root')
-            ->setExtra('request', $request)
-        ;
-
-        foreach ($this->pool->getAdminGroups() as $name => $group) {
-
-            // Check if the menu group is built by a menu provider
-            if (isset($group['provider'])) {
-                $subMenu = $this->knpHelper->get($group['provider']);
-
-                $menu->addChild($subMenu)
-                    ->setAttributes(array(
-                        'icon'            => $group['icon'],
-                        'label_catalogue' => $group['label_catalogue']
-                    ))
-                    ->setExtra('roles', $group['roles']);
-
-                continue;
-            }
-
-            // The menu group is built by config
-            $menu
-                ->addChild($name, array('label' => $group['label']))
-                ->setAttributes(
-                    array(
-                        'icon'             => $group['icon'],
-                        'label_catalogue'  => $group['label_catalogue'],
-                    )
-                )
-                ->setExtra('roles', $group['roles'])
-            ;
-
-            foreach ($group['items'] as $item) {
-                if (array_key_exists('admin', $item) && $item['admin'] != null) {
-                    $admin             = $this->pool->getInstance($item['admin']);
-
-                    // skip menu item if no `list` url is available or user doesn't have the LIST access rights
-                    if (!$admin->hasRoute('list') || !$admin->isGranted('LIST')) {
-                        continue;
-                    }
-
-                    $label             = $admin->getLabel();
-                    $route             = $admin->generateUrl('list');
-                    $translationDomain = $admin->getTranslationDomain();
-                } else {
-                    $label             = $item['label'];
-                    $route             = $this->router->generate($item['route'], $item['route_params']);
-                    $translationDomain = $group['label_catalogue'];
-                    $admin             = null;
-                }
-
-                $menu[$name]
-                    ->addChild($label, array('uri' => $route))
-                    ->setExtra('translationdomain', $translationDomain)
-                    ->setExtra('admin', $admin)
-                ;
-            }
-
-            if (0 === count($menu[$name]->getChildren())) {
-                $menu->removeChild($name);
-            }
-        }
-
-        return $menu;
-    }
 }