Skip to content

Instantly share code, notes, and snippets.

@sokil
Last active July 15, 2016 21:28
Show Gist options
  • Save sokil/a6b561ac42765a6a4581 to your computer and use it in GitHub Desktop.
Save sokil/a6b561ac42765a6a4581 to your computer and use it in GitHub Desktop.
Symfony Menu
{{ knp_menu_render('bundleName.main_menu') }}
<?php
namespace Vendor\Package\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Yaml\Yaml;
class Builder
{
/**
* @var FactoryInterface
*/
private $factory;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var AuthorizationCheckerInterface
*/
private $authorizationChecker;
private $configuration;
/**
* @param FactoryInterface $factory
*/
public function __construct(
FactoryInterface $factory,
TranslatorInterface $translator,
AuthorizationCheckerInterface $authorizationChecker,
$configurationPath
) {
$this->factory = $factory;
$this->translator = $translator;
$this->authorizationChecker = $authorizationChecker;
$this->configuration = Yaml::parse(file_get_contents($configurationPath));
}
public function build($manyName)
{
if (empty($this->configuration[$manyName])) {
throw new \Exception('Wrong menu name specified');
}
$menuConfig = $this->configuration[$manyName];
// init root
$rootItem = $this->factory->createItem('root', $menuConfig);
// init items
foreach ($menuConfig['items'] as $name => $item) {
// check role
if (isset($item['role']) && !$this->authorizationChecker->isGranted($item['role'])) {
continue;
}
// add item
$item['label'] = $this->translator->trans($item['label']);
$rootItem->addChild($name, $item);
}
return $rootItem;
}
}
main:
childrenAttributes:
class: nav navbar-nav
items:
- label: menu_item_1
role: ROLE_SOME_1
uri: /somePageUrl
- label: menu_item_2
route: some_symfony_route_name
- label: menu_new_task
uri: /someOtherUrl
role: ROLE_SOME_3
linkAttributes:
class: visible-xs
bottom:
childrenAttributes:
class: nav navbar-nav navbar-center
items:
- label: menu_item_1
role: ROLE_SOME_1
uri: /somePageUrl
- label: menu_item_2
route: some_symfony_route_name
bundleName.menu_builder:
class: Vendor\Package\Menu
arguments:
- @knp_menu.factory
- @translator
- @security.authorization_checker
- %kernel.root_dir%/config/menu.yml
bundleName.main_menu:
class: Knp\Menu\MenuItem
factory: [@bundleName.menu_builder, build]
arguments: ['main']
tags:
- { name: knp_menu.menu, alias: bundleName.main_menu }
bundleName.bottom_menu:
class: Knp\Menu\MenuItem
factory: [@bundleName.menu_builder, build]
arguments: ['bottom']
tags:
- { name: knp_menu.menu, alias: bundleName.bottom_menu }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment