Ejemplo n.º 1
0
 public function createMainMenu(TokenStorage $tokenStorage)
 {
     /** @var User $user */
     $user = $tokenStorage->getToken()->getUser();
     $menu = $this->factory->createItem('root', ['navbar' => true]);
     $layout = $menu->addChild('Главная страница', ['icon' => 'home', 'route' => 'homepage']);
     $layout = $menu->addChild('Архив игр', ['icon' => 'archive', 'route' => 'archive']);
     if ($user instanceof User) {
         $dropdown = $menu->addChild($user->getUsername(), ['dropdown' => true, 'caret' => true, 'icon' => 'user']);
         $dropdown->addChild('Профиль', ['route' => 'fos_user_profile_edit', 'icon' => 'user']);
         $dropdown->addChild('Выход', ['route' => 'fos_user_security_logout', 'icon' => 'sign-out']);
         $menu->addChild('Командные настройки', ['route' => 'team_settings', 'icon' => 'users']);
         if ($user->hasRole('ROLE_ADMIN')) {
             $menu->addChild('Администрирование домена', ['route' => 'sonata_admin_dashboard', 'icon' => 'edit']);
         }
     } else {
         $login = $menu->addChild('Вход', ['dropdown' => true, 'caret' => true, 'icon' => 'sign-in']);
         $login->addChild('ВКонтакте', ['route' => 'vkontakte_oauth', 'icon' => 'vk']);
         $login->addChild('Facebook', ['route' => 'facebook_oauth', 'icon' => 'facebook']);
         $login->addChild('Google+', ['route' => 'google_oauth', 'icon' => 'google-plus']);
         $login->addChild('Вход через логин/пароль', ['route' => 'fos_user_security_login', 'icon' => 'sign-in']);
         $menu->addChild('Регистрация', ['route' => 'fos_user_registration_register']);
         $menu->addChild('Сброс пароля', ['route' => 'fos_user_resetting_request']);
     }
     return $menu;
 }
Ejemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function register(Container $app)
 {
     $app['menu.factory'] = function ($app) {
         $factory = new MenuFactory();
         $factory->addExtension(new RoutingExtension($app['url_generator']));
         return $factory;
     };
     $app['menu.matcher'] = function ($app) {
         $matcher = new Matcher();
         if (isset($app['menu.matcher.configure'])) {
             $app['menu.matcher.configure']($matcher);
         }
         return $matcher;
     };
     $app['menu.matcher.configure'] = $app->protect(function (Matcher $matcher) use($app) {
         foreach ($app['menu.voters'] as $voter) {
             $matcher->addVoter($voter);
         }
     });
     $app['menu.voters'] = function ($app) {
         $request = $app['request_stack']->getMasterRequest();
         $voters = [];
         if (null !== $request) {
             $voters[] = new RouteVoter($request);
             $voters[] = new UriVoter($request->getRequestUri());
         }
         return $voters;
     };
     $app['menu.renderer.list'] = function ($app) {
         return new ListRenderer($app['menu.matcher'], [], $app['charset']);
     };
     $app['menu.provider'] = function ($app) {
         return new MenuProvider($app, $app['menus']);
     };
     if (!isset($app['menus'])) {
         $app['menus'] = [];
     }
     $app['menu.renderer'] = function ($app) {
         return new TwigRenderer($app['twig'], 'knp_menu.html.twig', $app['menu.matcher']);
     };
     $app['menu.renderer_provider'] = function ($app) {
         $app['menu.renderers'] = array_merge(['list' => 'menu.renderer.list'], ['twig' => 'menu.renderer'], isset($app['menu.renderers']) ? $app['menu.renderers'] : []);
         return new RendererProvider($app, 'twig', $app['menu.renderers']);
     };
     $app['menu.manipulator'] = function () {
         return new MenuManipulator();
     };
     $app['menu.helper'] = function ($app) {
         return new Helper($app['menu.renderer_provider'], $app['menu.provider'], $app['menu.manipulator']);
     };
     $app['menu.twig_extension'] = function ($app) {
         return new MenuExtension($app['menu.helper'], $app['menu.matcher'], $app['menu.manipulator']);
     };
     $app->extend('twig', function (\Twig_Environment $twig, $app) {
         $twig->addExtension($app['menu.twig_extension']);
         return $twig;
     });
 }
Ejemplo n.º 3
0
 public function register(Application $app)
 {
     $app['knp_menu.factory'] = $app->share(function () use($app) {
         $factory = new MenuFactory();
         if (isset($app['url_generator'])) {
             $factory->addExtension(new RoutingExtension($app['url_generator']));
         }
         return $factory;
     });
     $app['knp_menu.matcher'] = $app->share(function () use($app) {
         $matcher = new Matcher();
         if (isset($app['knp_menu.matcher.configure'])) {
             $app['knp_menu.matcher.configure']($matcher);
         }
         return $matcher;
     });
     $app['knp_menu.renderer.list'] = $app->share(function () use($app) {
         return new ListRenderer($app['knp_menu.matcher'], array(), $app['charset']);
     });
     $app['knp_menu.menu_provider'] = $app->share(function () use($app) {
         return new PimpleMenuProvider($app, $app['knp_menu.menus']);
     });
     if (!isset($app['knp_menu.menus'])) {
         $app['knp_menu.menus'] = array();
     }
     $app['knp_menu.renderer_provider'] = $app->share(function () use($app) {
         $app['knp_menu.renderers'] = array_merge(array('list' => 'knp_menu.renderer.list'), isset($app['knp_menu.renderer.twig']) ? array('twig' => 'knp_menu.renderer.twig') : array(), isset($app['knp_menu.renderers']) ? $app['knp_menu.renderers'] : array());
         return new PimpleRendererProvider($app, $app['knp_menu.default_renderer'], $app['knp_menu.renderers']);
     });
     $app['knp_menu.menu_manipulator'] = $app->share(function () use($app) {
         return new MenuManipulator();
     });
     if (!isset($app['knp_menu.default_renderer'])) {
         $app['knp_menu.default_renderer'] = 'list';
     }
     $app['knp_menu.helper'] = $app->share(function () use($app) {
         return new Helper($app['knp_menu.renderer_provider'], $app['knp_menu.menu_provider'], $app['knp_menu.menu_manipulator']);
     });
     if (isset($app['twig'])) {
         $app['knp_menu.twig_extension'] = $app->share(function () use($app) {
             return new MenuExtension($app['knp_menu.helper'], $app['knp_menu.matcher'], $app['knp_menu.menu_manipulator']);
         });
         $app['knp_menu.renderer.twig'] = $app->share(function () use($app) {
             return new TwigRenderer($app['twig'], $app['knp_menu.template'], $app['knp_menu.matcher']);
         });
         if (!isset($app['knp_menu.template'])) {
             $app['knp_menu.template'] = 'knp_menu.html.twig';
         }
         $app['twig'] = $app->share($app->extend('twig', function (\Twig_Environment $twig) use($app) {
             $twig->addExtension($app['knp_menu.twig_extension']);
             return $twig;
         }));
         $app['twig.loader.filesystem'] = $app->share($app->extend('twig.loader.filesystem', function (\Twig_Loader_Filesystem $loader) use($app) {
             $loader->addPath(__DIR__ . '/../../Resources/views');
             return $loader;
         }));
     }
 }
Ejemplo n.º 4
0
 public function testCreateItem()
 {
     $factory = new MenuFactory();
     $item = $factory->createItem('test', array('uri' => 'http://example.com', 'linkAttributes' => array('class' => 'foo'), 'display' => false, 'displayChildren' => false));
     $this->assertInstanceOf('Knp\\Menu\\ItemInterface', $item);
     $this->assertEquals('test', $item->getName());
     $this->assertFalse($item->isDisplayed());
     $this->assertFalse($item->getDisplayChildren());
     $this->assertEquals('foo', $item->getLinkAttribute('class'));
 }
 public function testFromArrayWithChildrenOmittingName()
 {
     $factory = new MenuFactory();
     $array = array('name' => 'joe', 'children' => array('jack' => array('label' => 'Jack'), 'john' => array('label' => 'John')));
     $item = $factory->createFromArray($array);
     $this->assertEquals('joe', $item->getName());
     $this->assertEmpty($item->getAttributes());
     $this->assertCount(2, $item);
     $this->assertTrue(isset($item['john']));
     $this->assertTrue(isset($item['jack']));
 }
 /**
  * transform cached data into menu items
  *
  * @param array $children
  * @param ItemInterface|null $parent
  * @return array
  */
 public function transformToMenuData(array $children, ItemInterface $parent = null)
 {
     $menuChildren = array();
     foreach ($children as $childItem) {
         $menuItem = $this->menuFactory->createItem($childItem['name'], array('uri' => $childItem['uri'], 'attributes' => array('title' => $childItem['title'])));
         if (isset($childItem['children'])) {
             $this->transformToMenuData($childItem['children'], $menuItem);
         }
         $parent ? $parent->addChild($menuItem) : ($menuChildren[] = $menuItem);
     }
     return $menuChildren;
 }
 /**
  * Init Mock
  */
 public function setUp()
 {
     $routingExtension = $this->getMockBuilder('Knp\\Menu\\Integration\\Symfony\\RoutingExtension')->disableOriginalConstructor()->getMock();
     $routingExtension->expects($this->any())->method('buildOptions')->will($this->returnValue(array('uri' => '/my-page')));
     $securityContext = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\SecurityContextInterface')->disableOriginalConstructor()->getMock();
     $securityContext->expects($this->any())->method('isGranted')->will($this->returnValue(true));
     $menuFactory = new MenuFactory();
     $menuFactory->addExtension($routingExtension);
     $eventDispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
     $configuration = JbConfigKnpMenuExtensionTest::loadConfiguration();
     $this->configurationProvider = new ConfigurationMenuProvider($menuFactory, $eventDispatcher, $securityContext);
     $this->configurationProvider->setConfiguration($configuration);
 }
Ejemplo n.º 8
0
 protected function setUp()
 {
     $factory = new MenuFactory();
     $this->menu = $factory->createItem('Root li', array('childrenAttributes' => array('class' => 'root')));
     $this->pt1 = $this->menu->addChild('Parent 1');
     $this->ch1 = $this->pt1->addChild('Child 1');
     $this->ch2 = $this->pt1->addChild('Child 2');
     // add the 3rd child via addChild with an object
     $this->ch3 = new MenuItem('Child 3', $factory);
     $this->pt1->addChild($this->ch3);
     $this->pt2 = $this->menu->addChild('Parent 2');
     $this->ch4 = $this->pt2->addChild('Child 4');
     $this->gc1 = $this->ch4->addChild('Grandchild 1');
 }
Ejemplo n.º 9
0
 /**
  * Get Menu
  *
  * Returns a KNP Menu object, which can be traversed or rendered
  *
  * @param string  $markup    Content to get items fro $this->getItems($markup, $topLevel, $depth)m
  * @param int     $topLevel  Top Header (1 through 6)
  * @param int     $depth     Depth (1 through 6)
  * @return ItemInterface     KNP Menu
  */
 public function getMenu($markup, $topLevel = 1, $depth = 6)
 {
     // Setup an empty menu object
     $menu = $this->menuFactory->createItem('TOC');
     // Empty?  Do nothing.
     if (trim($markup) == '') {
         return [];
     }
     // Parse HTML
     $tagsToMatch = $this->determineHeaderTags($topLevel, $depth);
     $parsed = $this->domParser->str_get_html($markup);
     // Runtime exception for bad code
     if (!$parsed) {
         throw new RuntimeException("Could not parse HTML");
     }
     // Extract items
     // Initial settings
     $lastElem = $menu;
     // Do it...
     foreach ($parsed->find(implode(', ', $tagsToMatch)) as $element) {
         // Skip items without IDs
         if (!$element->id) {
             continue;
         }
         // Get the TagName and the level
         $tagName = $element->tag;
         $level = array_search(strtolower($tagName), $tagsToMatch) + 1;
         // Determine parent item which to add child
         if ($level == 1) {
             $parent = $menu;
         } elseif ($level == $lastElem->getLevel()) {
             $parent = $lastElem->getParent();
         } elseif ($level > $lastElem->getLevel()) {
             $parent = $lastElem;
             for ($i = $lastElem->getLevel(); $i < $level - 1; $i++) {
                 $parent = $parent->addChild('');
             }
         } else {
             //if ($level < $lastElem->getLevel())
             $parent = $lastElem->getParent();
             while ($parent->getLevel() > $level - 1) {
                 $parent = $parent->getParent();
             }
         }
         $lastElem = $parent->addChild($element->title ?: $element->plaintext, ['uri' => '#' . $element->id]);
     }
     return $menu;
 }
Ejemplo n.º 10
0
 /**
  * @param MenuFactory $menuFactory
  * @param string      $label
  * @param int         $order
  * @param array       $childs
  * @return \Knp\Menu\MenuItem
  */
 public function createItemWithChilds(MenuFactory $menuFactory, $label, $order, array $childs)
 {
     $menuItem = $menuFactory->createItem($label, array('uri' => '#', 'label' => $label));
     $menuItem->setExtra('orderNumber', $order);
     // add the childs
     foreach ($childs as $key => $value) {
         // if the value is a string we can expect this is a simple child
         if (is_string($value)) {
             $child = $menuFactory->createItem($key, array('route' => $value, 'label' => $key));
         } else {
             $child = $value;
         }
         $menuItem->addChild($child);
     }
     return $menuItem;
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  *
  * @covers Kunstmaan\NodeBundle\Helper\Menu\ActionsMenuBuilder::__construct
  */
 protected function setUp()
 {
     /* @var UrlGeneratorInterface $urlGenerator */
     $urlGenerator = $this->getMock('Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface');
     $routingExtension = new RoutingExtension($urlGenerator);
     $factory = new MenuFactory();
     $factory->addExtension($routingExtension);
     $em = $this->getMockedEntityManager();
     /* @var EventDispatcherInterface $dispatcher */
     $dispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface');
     /* @var RouterInterface $router */
     $router = $this->getMock('Symfony\\Component\\Routing\\RouterInterface');
     $authorizationChecker = $this->getMock('Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationCheckerInterface');
     $authorizationChecker->expects($this->any())->method('isGranted')->will($this->returnValue(true));
     $this->builder = new ActionsMenuBuilder($factory, $em, $router, $dispatcher, $authorizationChecker, new PagesConfiguration([]));
 }
 public function createItem($name, array $options = array())
 {
     if (!empty($options['route'])) {
         $params = isset($options['routeParameters']) ? $options['routeParameters'] : array();
         $absolute = isset($options['routeAbsolute']) ? $options['routeAbsolute'] : false;
         $options['uri'] = $this->generator->generate($options['route'], $params, $absolute);
     }
     return parent::createItem($name, $options);
 }
Ejemplo n.º 13
0
 public function getMenu()
 {
     $menuList = $this->factory->createItem($this->name);
     foreach ($this->menu as $name => $menuItem) {
         if ($this->securityContext->isGranted($menuItem['role'])) {
             $menu = $this->factory->createItem($name, array('route' => $menuItem['route']));
             $menu->setLabel($menuItem['label']);
             if (isset($menuItem['translationDomain'])) {
                 $menu->setLabelAttribute('translationDomain', $menuItem['translationDomain']);
             }
             $menuList->addChild($menu);
         }
     }
     $event = new MenuEvent();
     $event->setMenu($menuList);
     $this->dispatcher->dispatch($this->name, $event);
     return $event->getMenu();
 }
Ejemplo n.º 14
0
 public function createPageMenu()
 {
     $factory = new MenuFactory();
     $pages = $this->getBag()->get('pageRepository')->findAll();
     $menu = $factory->createItem('root');
     $this->setMenuAttributes('root', $menu);
     foreach ($pages as $path => $page) {
         if (strpos($path, '/')) {
             $parents = explode('/', $path);
             $child = array_pop($parents);
             $this->addToParent($menu, $parents, $child, $page);
         } else {
             $this->addToMenu($menu, $path, $page);
         }
     }
     $this->setMenu($menu);
     $this->triggerEvent('navigationCreatePageMenuAfter', array('navigation' => $this));
     return $this;
 }
Ejemplo n.º 15
0
 /**
  * Get Menu
  *
  * Returns a KNP Menu object, which can be traversed or rendered
  *
  * @param string  $markup    Content to get items fro $this->getItems($markup, $topLevel, $depth)m
  * @param int     $topLevel  Top Header (1 through 6)
  * @param int     $depth     Depth (1 through 6)
  * @return ItemInterface     KNP Menu
  */
 public function getMenu($markup, $topLevel = 1, $depth = 6)
 {
     // Setup an empty menu object
     $menu = $this->menuFactory->createItem('TOC');
     // Empty?  Do nothing.
     if (trim($markup) == '') {
         return [];
     }
     // Parse HTML
     $tagsToMatch = $this->determineHeaderTags($topLevel, $depth);
     // Initial settings
     $lastElem = $menu;
     // Do it...
     $domDocument = $this->domParser->loadHTML($markup);
     foreach ($this->traverseHeaderTags($domDocument, $topLevel, $depth) as $node) {
         // Skip items without IDs
         if (!$node->hasAttribute('id')) {
             continue;
         }
         // Get the TagName and the level
         $tagName = $node->tagName;
         $level = array_search(strtolower($tagName), $tagsToMatch) + 1;
         // Determine parent item which to add child
         if ($level == 1) {
             $parent = $menu;
         } elseif ($level == $lastElem->getLevel()) {
             $parent = $lastElem->getParent();
         } elseif ($level > $lastElem->getLevel()) {
             $parent = $lastElem;
             for ($i = $lastElem->getLevel(); $i < $level - 1; $i++) {
                 $parent = $parent->addChild('');
             }
         } else {
             //if ($level < $lastElem->getLevel())
             $parent = $lastElem->getParent();
             while ($parent->getLevel() > $level - 1) {
                 $parent = $parent->getParent();
             }
         }
         $lastElem = $parent->addChild($node->getAttribute('title') ?: $node->textContent, ['uri' => '#' . $node->getAttribute('id')]);
     }
     return $menu;
 }
Ejemplo n.º 16
0
 /**
  * Build the menu
  *
  * @param ContentInterface $content
  *
  * @return \Knp\Menu\MenuItem
  */
 public function build(ContentInterface $content)
 {
     $menu = null;
     if (count($this->locales) > 1) {
         $factory = new MenuFactory();
         $menu = $factory->createItem('ContentMenu', $this->locales);
         $menu->addChild('default', ['uri' => $this->router->generate('opifer.cms.content.edit', ['id' => $content->getId() ? $content->getId() : 0, 'locale' => null]), 'label' => $this->translator->trans('Default')]);
         foreach ($this->locales as $plocale) {
             if ($plocale === $this->defaultLocale) {
                 continue;
             }
             $menu->addChild($plocale, ['uri' => $this->router->generate('opifer.cms.content.edit', ['id' => $content->getId() ? $content->getId() : 0, 'locale' => $plocale]), 'label' => $this->translator->trans($plocale)]);
         }
         foreach ($menu->getChildren() as $menuChild) {
             if ($menuChild->getName() == $locale) {
                 $menuChild->setCurrent(true);
             }
             if ($menuChild->getName() == 'default' && $locale == null) {
                 $menuChild->setCurrent(true);
             }
         }
     }
     return $menu;
 }
 /**
  * @dataProvider hasInCacheDataProvider
  * @param boolean $hasInCache
  */
 public function testRouteCaching($hasInCache)
 {
     $params = array('id' => 20);
     $uriKey = md5('route_uri:route_name' . serialize($params));
     $aclKey = md5('route_acl:route_name');
     $cache = $this->getMockBuilder('Doctrine\\Common\\Cache\\ArrayCache')->getMock();
     $cache->expects($this->exactly(2))->method('contains')->will($this->returnValueMap(array(array($uriKey, $hasInCache), array($aclKey, $hasInCache))));
     if ($hasInCache) {
         $cache->expects($this->exactly(2))->method('fetch')->will($this->returnValueMap(array(array($uriKey, '/'), array($aclKey, 'controller::action'))));
     } else {
         $cache->expects($this->exactly(2))->method('save')->with($this->logicalOr($this->equalTo($aclKey), $this->equalTo('controller::action'), $this->equalTo($uriKey), $this->equalTo('/')));
     }
     $this->factoryExtension->setCache($cache);
     $options = array('route' => 'route_name', 'routeParameters' => $params);
     $this->assertRouteByRouteNameCalls(true, 'route_name', 'controller', 'action', (int) (!$hasInCache));
     $item = $this->factory->createItem('test', $options);
     $this->assertTrue($item->getExtra('isAllowed'));
     $this->assertInstanceOf('Knp\\Menu\\MenuItem', $item);
 }
Ejemplo n.º 18
0
 /**
  * Create a MenuItem. This triggers the voters to decide if its the current
  * item.
  *
  * You can add custom link types by overwriting this method and calling the
  * parent - setting the URI option and the linkType to "uri".
  *
  * @param string $name    the menu item name
  * @param array  $options options for the menu item, we care about 'content'
  *
  * @throws \RuntimeException If the stored link type is not known.
  * @return MenuItem|null Returns null if no route can be built for this menu item,
  *
  */
 public function createItem($name, array $options = [])
 {
     $options = array_merge(['content' => null, 'routeParameters' => [], 'attributes' => [], 'linkAttributes' => [], 'childrenAttributes' => [], 'labelAttributes' => [], 'routeAbsolute' => false, 'uri' => null, 'route' => null, 'current' => null, 'linkType' => null], $options);
     if (null === $options['linkType']) {
         $options['linkType'] = $this->determineLinkType($options);
     }
     if (!is_array($options['routeParameters'])) {
         $options['routeParameters'] = [];
     }
     if (!is_array($options['attributes'])) {
         $options['attributes'] = [];
     }
     if (!is_array($options['linkAttributes'])) {
         $options['linkAttributes'] = [];
     }
     if (!is_array($options['childrenAttributes'])) {
         $options['childrenAttributes'] = [];
     }
     if (!is_array($options['labelAttributes'])) {
         $options['labelAttributes'] = [];
     }
     $this->validateLinkType($options['linkType']);
     switch ($options['linkType']) {
         case 'content':
             try {
                 $options['uri'] = $this->contentRouter->generate($options['content'], $options['routeParameters'], $options['routeAbsolute']);
             } catch (RouteNotFoundException $e) {
                 if (!$this->allowEmptyItems) {
                     return;
                 }
             } catch (\Exception $e) {
                 $this->logger->error(sprintf('%s : %s', $name, $e->getMessage()));
                 return;
             }
             unset($options['route']);
             break;
         case 'uri':
             unset($options['route']);
             break;
         case 'route':
             unset($options['uri']);
             try {
                 $options['uri'] = $this->generator->generate($options['route'], $options['routeParameters'], $options['routeAbsolute']);
                 // $options['uri'] = "http://www.zapoyok.info";
                 unset($options['route']);
             } catch (RouteNotFoundException $e) {
                 $this->logger->error(sprintf('%s : %s', $name, $e->getMessage()));
                 if (!$this->allowEmptyItems) {
                     return;
                 }
             } catch (\Exception $e) {
                 $this->logger->error(sprintf('%s : %s', $name, $e->getMessage()));
                 return;
             }
             break;
         default:
             throw new \RuntimeException(sprintf('Internal error: unexpected linkType "%s"', $options['linkType']));
     }
     $item = parent::createItem($name, $options);
     $item->setExtra('content', $options['content']);
     $current = $this->isCurrentItem($item);
     if ($current) {
         $item->setCurrent(true);
     }
     return $item;
 }
Ejemplo n.º 19
0
 public function getSectionsMenu($options)
 {
     /*
      * Настроки кеширования
      */
     $env = $this->container->getParameter("kernel.environment");
     $cacheDriver = new \Doctrine\Common\Cache\ApcuCache();
     $namespace = 'menu_section_' . $env . '_' . $options['BLOCK_ID'];
     $cacheDriver->setNamespace($namespace);
     // засекаем время
     $time_start = microtime(1);
     /*
      * Добавляем текущую страницу в id кеша
      */
     $request = $this->container->get('request_stack');
     $routeParams = $request->getCurrentRequest()->get('_route_params');
     $currentCode = false;
     if (array_key_exists('CODE', $routeParams)) {
         $currentCode = trim($routeParams['CODE'], '/');
     }
     $options['@currentCode'] = $currentCode;
     //echo '<pre>' . print_r($options, true) . '</pre>';
     // id кеша
     $cacheId = json_encode($options);
     //if ($fooString = $cacheDriver->fetch($cacheId)) {
     if (false) {
         /*
          * Выдаем результат из кеша
          */
         $result = unserialize($fooString);
     } else {
         /*
          * Генерируем результат
          */
         $SectionClass = $this->container->get('SectionClass');
         $tree = $SectionClass->SectionsList(array('block_id' => $options['BLOCK_ID']));
         //echo '<pre>' . print_r('tree on SectionMenu', true) . '</pre>';
         //echo '<pre>' . print_r($tree, true) . '</pre>';
         $factory = new MenuFactory();
         $menu = $factory->createItem('root');
         //echo '<pre>' . print_r($routeName, true) . '</pre>';
         //echo '<pre>' . print_r($routeParams, true) . '</pre>';
         $this->generateMenuFromTree($tree, $menu, $options['route'], $currentCode);
         $menuRenderer = $this->getMenuRenderer();
         $result = $menuRenderer->render($menu, array('template' => $options['template'], 'currentAsLink' => false));
         /*
          * Сохраняем результат в кеш
          */
         $cacheDriver->save($cacheId, serialize($result));
     }
     $time_end = microtime(1);
     $time = number_format(($time_end - $time_start) * 1000, 2);
     return html_entity_decode($result);
     //echo $time.' мс';
 }
 /**
  * Create a new MenuItem
  *
  * @param string $name
  * @param string $uri
  * @param array $attributes
  * @return \Knp\Menu\MenuItem
  */
 protected function createMenu($name = 'test_menu', $uri = 'homepage', array $attributes = array())
 {
     $factory = new MenuFactory();
     return $factory->createItem($name, array('attributes' => $attributes, 'uri' => $uri));
 }
 /**
  * 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;
 }
Ejemplo n.º 22
0
 /**
  * Edit an existing menu item.
  *
  * @Route(
  *     "/menu/edit/{id}/{type}/{locale}",
  *     name="opifer_cms_menu_edit"
  * )
  *
  * @param Request $request
  * @param integer $id
  * @param string  $type
  * @param string  $locale
  *
  * @return Response
  */
 public function editAction(Request $request, $id = 0, $type = 'item', $locale = null)
 {
     $em = $this->getDoctrine()->getManager();
     $locales = $this->container->getParameter('opifer_cms.allowed_locales');
     $defaultLocale = $this->container->getParameter('locale');
     $tr = $this->get('translator');
     $menu = $this->get('doctrine')->getRepository('OpiferCmsBundle:Menu')->findOneById($id);
     if ($locale !== null) {
         $menu->setTranslatableLocale($locale);
         $em->refresh($menu);
     }
     if (!$menu) {
         throw $this->createNotFoundException('No menu found for id ' . $id);
     }
     if (count($locales) > 1) {
         $factory = new MenuFactory();
         $localeMenu = $factory->createItem('localeMenu');
         $localeMenu->addChild('default', array('uri' => $this->generateUrl('opifer_cms_menu_edit', ['id' => $menu->getId() ? $menu->getId() : 0]), 'label' => $tr->trans('Default')));
         foreach ($locales as $plocale) {
             if ($plocale === $defaultLocale) {
                 continue;
             }
             $localeMenu->addChild($plocale, ['uri' => $this->generateUrl('opifer_cms_menu_edit', ['id' => $menu->getId() ? $menu->getId() : 0, 'locale' => $plocale]), 'label' => $tr->trans($plocale)]);
         }
         foreach ($localeMenu->getChildren() as $localeMenuChild) {
             if ($localeMenuChild->getName() == $locale) {
                 $localeMenuChild->setCurrent(true);
             }
             if ($localeMenuChild->getName() == 'default' && $locale == null) {
                 $localeMenuChild->setCurrent(true);
             }
         }
     }
     $form = $this->createForm('admin_menu', $menu);
     $form->handleRequest($request);
     if ($form->isValid()) {
         $em->persist($menu);
         $em->flush();
         return $this->redirect($this->generateUrl('opifer_cms_menu_index', ['locale' => $locale]));
     }
     return $this->render('OpiferCmsBundle:Menu:edit.html.twig', ['menu' => $menu, 'localeMenu' => isset($localeMenu) ? $localeMenu : '', 'form' => $form->createView()]);
 }
Ejemplo n.º 23
0
 protected function processMenu()
 {
     $links = $this->menuRepo->getMenuTree();
     $factory = new MenuFactory();
     $menu = $factory->createItem('root');
     $menu->setChildrenAttribute('class', 'nav navbar-nav');
     foreach ($links as $link) {
         $this->processMenuLink($menu, $link);
     }
     return $menu;
 }
Ejemplo n.º 24
0
 public function creatMenu()
 {
     $factory = new MenuFactory();
     $itemMatcher = new \Knp\Menu\Matcher\Matcher();
     $renderer = new \Knp\Menu\Renderer\ListRenderer($itemMatcher);
     $menu = $factory->createItem('My menu');
     foreach ($this->presetName as $url) {
         $menu->addChild($url, array('uri' => '?preset=' . $url));
     }
     $this->rendererMenu = $renderer;
     $this->menuData = $menu;
     return $this;
 }
Ejemplo n.º 25
0
 private function getMenu($options, $array)
 {
     if (!array_key_exists('template', $options)) {
         $options['template'] = 'default.html.twig';
     }
     $factory = new MenuFactory();
     $menu = $factory->createItem('root');
     //$menu->setCurrentAsLink(false); // не работает
     foreach ($array as $e) {
         $item = $menu->addChild($e['name'], array('uri' => $e['url'], 'attributes' => array('data-url' => $e['url'], 'data-uri' => $_SERVER['REQUEST_URI'])));
         if ($_SERVER['REQUEST_URI'] == '' . $e['url'] . '') {
             //echo '<pre>' . print_r($_SERVER['REQUEST_URI'], true) . '</pre>';
             //echo '<pre>' . print_r($e['url'], true) . '</pre>';
             $item->setCurrent(true);
         }
     }
     $menuRenderer = $this->getMenuRenderer();
     $result = $menuRenderer->render($menu, array('template' => $options['template'], 'currentAsLink' => false));
     return $result;
 }
Ejemplo n.º 26
0
 /**
  * @return \Knp\Menu\MenuItem
  */
 protected function configureTreeMenu($object, \Knp\Menu\MenuFactory $factory, \Knp\Menu\MenuItem $child = null)
 {
     if (!$object) {
         $options = array();
         if ($this->auth('list', $object)) {
             $options['uri'] = $this->path('list', 0);
         } else {
             $options['labelAttributes']['class'] = 'sf_action_tree_nolink';
         }
         $menu = $factory->createItem($this->trans('sf.tree.root', array('%admin%' => $this->getLabel()), $this->sf_domain), $options);
         if (!$this->tree_object_id) {
             $menu->setCurrent(true);
         }
         if ($child) {
             $menu->addChild($child);
         }
         return $menu;
     }
     $options = array();
     if ($this->auth('list', $object)) {
         $options['uri'] = $this->path('list', $object);
     } else {
         $options['labelAttributes']['class'] = 'sf_action_tree_nolink';
     }
     $menu = $factory->createItem($this->string($object), $options);
     if ($this->getReflectionProperty($this->property_id_name)->getValue($object) == $this->tree_object_id) {
         $menu->setCurrent(true);
     }
     if ($child) {
         $menu->addChild($child);
     }
     $parent = $this->getReflectionProperty($this->tree['parent'])->getValue($object);
     return $this->configureTreeMenu($parent, $factory, $menu);
 }
Ejemplo n.º 27
0
 public function __construct(UrlGeneratorInterface $generator)
 {
     trigger_error(__CLASS__ . ' is deprecated. Use Knp\\Menu\\Silex\\RoutingExtension instead.', E_USER_DEPRECATED);
     parent::__construct();
     $this->addExtension(new RoutingExtension($generator));
 }
Ejemplo n.º 28
0
 public function configureSpaceMenu()
 {
     $factory = new MenuFactory();
     $this->spaceMenu = $factory->createItem('Space menu');
     $this['twig']->addGlobal('space_menu', $this->spaceMenu);
 }
Ejemplo n.º 29
0
 public function __construct()
 {
     parent::__construct();
     $this->addExtension(new CoreExtension(), -10);
 }
Ejemplo n.º 30
0
 private function getMenu($options, $array, $menu = false, $currentItem = false)
 {
     //$array = $this->menuByParents['root'];
     $factory = new MenuFactory();
     if ($menu == false) {
         $menu = $factory->createItem('root');
     }
     //echo '<pre>' . print_r($array, true) . '</pre>';
     //exit;
     foreach ($array as $e) {
         $e['name'] = html_entity_decode($this->typograf($e['name']));
         if (preg_match('/^(http|https|ftp):\\/\\//', $e['url'])) {
             $url = $e['url'];
         } else {
             if (preg_match('/\\.(html|xml|php|htm)$/', $e['url'])) {
                 $url = $this->urlGenerator->generate('cmf_page_frontend_clear', array('name' => $e['url']));
             } else {
                 if ($e['url'] == '/') {
                     $url = $this->urlGenerator->generate('main');
                 } else {
                     $url = $this->urlGenerator->generate('cmf_page_frontend', array('name' => $e['url']));
                 }
             }
         }
         $item = $menu->addChild($e['name'], array('uri' => $url, 'attributes' => array()));
         $pathInfo = $this->container->get('request_stack')->getCurrentRequest()->getRequestUri();
         //echo '<pre>' . print_r($pathInfo->getRequestUri(), true) . '</pre>';
         //echo '<pre>' . print_r($url, true) . '</pre>';
         if ($pathInfo == '' . $url . '') {
             $item->setCurrent(true);
         }
         /**
          * Здесь делаем проверку параметров пункта меню, и если есть привязки - генерируем дерево по принципу getArray()
          */
         if ($e['__children']) {
             $currentItem = $e;
             $this->getMenu($options, $e['__children'], $item, $currentItem);
         }
     }
     if (!array_key_exists('template', $options)) {
         $options['template'] = 'default.html.twig';
     }
     $menuRenderer = $this->getMenuRenderer();
     $result = $menuRenderer->render($menu, array('template' => $options['template'], 'currentAsLink' => false));
     return $result;
 }