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; }
/** * 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; }
/** * 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; }
/** * @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; }
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); }
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(); }
/** * 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; }
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')); }
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'); }
/** * @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); }
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; }
/** * 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; }
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; }
/** * 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)); }
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; }
/** * 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()]); }
/** * @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); }
/** * 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; }
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; }
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; }
/** * 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; }
public function configureSpaceMenu() { $factory = new MenuFactory(); $this->spaceMenu = $factory->createItem('Space menu'); $this['twig']->addGlobal('space_menu', $this->spaceMenu); }
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.' мс'; }