Merge branch 'bugfix/activate-menu-entry-based-on-the-url-6153'

fixes #6153
This commit is contained in:
Johannes Meyer 2014-07-03 15:47:04 +02:00
commit 298edbe730
9 changed files with 556 additions and 529 deletions

View File

@ -2,6 +2,7 @@
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
use Icinga\Web\MenuRenderer;
use Icinga\Web\Controller\ActionController;
use Icinga\Web\Hook;
use Icinga\Web\Menu;
@ -17,9 +18,7 @@ class LayoutController extends ActionController
*/
public function menuAction()
{
$this->view->url = Url::fromRequest()->getRelativeUrl();
$this->view->items = Menu::fromConfig()->getChildren();
$this->view->sub = false;
$this->view->menuRenderer = new MenuRenderer(Menu::fromConfig()->order(), Url::fromRequest()->getRelativeUrl());
}
/**

View File

@ -1,33 +0,0 @@
<?php
if (! $this->level) {
$this->level = 0;
}
?>
<ul<?= $this->level === 0 ? ' role="navigation"' : '' ?>>
<?php
foreach ($this->items as $item) {
printf(
' <li%s><a href="%s">%s%s</a>',
$this->href($this->url) === $this->href($item->getUrl()) ? ' class="active"' : '',
$item->getUrl() ? $this->href($item->getUrl()) : '#',
$item->getIcon() ? $this->img(
$item->getIcon(),
array('class' => 'icon')
) . ' ' : '',
$this->escape($item->getTitle())
);
if ($item->hasChildren()) {
echo $this->partial(
'parts/menu.phtml',
array('items' => $item->getChildren(), 'url' => $this->url, 'level' => $this->level + 1)
);
}
echo "</li>\n";
}
?>
</ul>

View File

@ -2,22 +2,17 @@
use Icinga\Web\Url;
use Icinga\Web\Menu;
use Icinga\Web\MenuRenderer;
// Don't render a menu for unauthenticated users unless menu is auth aware
if (! $this->auth()->isAuthenticated()) {
return;
}
// Current url
$url = Url::fromRequest()->getRelativeUrl();
$menu = Menu::fromConfig();
?>
<div id="menu" data-base-target="_main">
<form action="<?= $this->href('search') ?>" method="get" role="search">
<input type="text" name="q" class="search autofocus" placeholder="<?= $this->translate('Search...') ?>" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
</form>
<?= $this->partial('parts/menu.phtml', array(
'items' => $menu->getChildren(),
'url' => $url
)) ?>
<?= new MenuRenderer(Menu::fromConfig()->order(), Url::fromRequest()->getRelativeUrl()); ?>
</div>

View File

@ -1,39 +1 @@
<ul>
<?php foreach ($items as $item): ?>
<?php
$itemClass = '';
if ($sub) {
// $itemClass .= 'submenu ';
}
if ($this->href($url) === $this->href($item->getUrl())) {
$itemClass .= 'active ';
}
?>
<li <?php if (!empty($itemClass)): ?>class="<?= $itemClass ?>"<?php endif ?>>
<?php if($item->getUrl()): ?>
<a href="<?= $this->href($item->getUrl()); ?>" <?php foreach($item->getAttribs() as $attrib => $value): ?> <?= $attrib ?>="<?= $value ?>"<?php endforeach?>>
<?php endif; ?>
<?php
if ($icon = $item->getIcon()) {
echo $this->img($icon, array('height' => 16, 'width' => 16));
}
?>
<?php if ($iconClass = $item->getIconClass()): ?>
<i class="<?= $iconClass ?>"></i>
<?php endif ?>
<?= $item->getTitle();?>
<?php if($item->getUrl()): ?>
</a>
<?php endif; ?>
<?php
if($item->hasChildren()) {
echo $this->partial(
'layout/menu.phtml',
'default',
array('items' => $item->getChildren(), 'sub' => true, 'url' => $this->url)
);
}
?>
</li>
<?php endforeach ?>
</ul>
<?= $menuRenderer; ?>

View File

@ -1,41 +1,83 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga Web 2.
*
* Icinga Web 2 - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Web;
use Icinga\Logger\Logger;
use Zend_Config;
use RecursiveIterator;
use Icinga\Application\Config;
use Icinga\Application\Icinga;
use Icinga\Exception\NotReadableError;
use Icinga\Exception\ProgrammingError;
class Menu extends MenuItem
class Menu implements RecursiveIterator
{
/**
* The id of this menu
*
* @type string
*/
protected $id;
/**
* The title of this menu
*
* Used for sorting when priority is unset or equal to other items
*
* @type string
*/
protected $title;
/**
* The priority of this menu
*
* Used for sorting
*
* @type int
*/
protected $priority = 100;
/**
* The url of this menu
*
* @type string
*/
protected $url;
/**
* The path to the icon of this menu
*
* @type string
*/
protected $icon;
/**
* The sub menus of this menu
*
* @type array
*/
protected $subMenus = array();
/**
* Create a new menu
*
* @param int $id The id of this menu
* @param Zend_Config $config The configuration for this menu
*/
public function __construct($id, Zend_Config $config = null)
{
$this->id = $id;
if ($config !== null) {
foreach ($config as $key => $value) {
$method = 'set' . implode('', array_map('ucfirst', explode('_', strtolower($key))));
if (method_exists($this, $method)) {
$this->{$method}($value);
}
}
}
}
/**
* Create menu from the application's menu config file plus the config files from all enabled modules
*
@ -45,35 +87,236 @@ class Menu extends MenuItem
{
$menu = new static('menu');
$manager = Icinga::app()->getModuleManager();
try {
$menuConfigs = array(Config::app('menu'));
} catch (NotReadableError $e) {
Logger::error($e);
$menuConfigs = array();
}
try {
$modules = $manager->listEnabledModules();
} catch (NotReadableError $e) {
Logger::error($e);
$modules = array();
}
$modules = $manager->listEnabledModules();
$menuConfigs = array(Config::app('menu'));
foreach ($modules as $moduleName) {
try {
$moduleMenuConfig = Config::module($moduleName, 'menu');
} catch (NotReadableError $e) {
Logger::error($e);
$moduleMenuConfig = array();
}
if (!empty($moduleMenuConfig)) {
$moduleMenuConfig = Config::module($moduleName, 'menu');
if (false === empty($moduleMenuConfig)) {
$menuConfigs[] = $moduleMenuConfig;
}
}
return $menu->loadMenuItems($menu->flattenConfigs($menuConfigs));
return $menu->loadSubMenus($menu->flattenConfigs($menuConfigs));
}
/**
* Set the id of this menu
*
* @param string $id The id to set for this menu
*
* @return self
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Return the id of this menu
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Set the title of this menu
*
* @param string $title The title to set for this menu
*
* @return self
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Return the title of this menu if set, otherwise its id
*
* @return string
*/
public function getTitle()
{
return $this->title ? $this->title : $this->id;
}
/**
* Set the priority of this menu
*
* @param int $priority The priority to set for this menu
*
* @return self
*/
public function setPriority($priority)
{
$this->priority = (int) $priority;
return $this;
}
/**
* Return the priority of this menu
*
* @return int
*/
public function getPriority()
{
return $this->priority;
}
/**
* Set the url of this menu
*
* @param string $url The url to set for this menu
*
* @return self
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Return the url of this menu
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set the path to the icon of this menu
*
* @param string $path The path to the icon for this menu
*
* @return self
*/
public function setIcon($path)
{
$this->icon = $path;
return $this;
}
/**
* Return the path to the icon of this menu
*
* @return string
*/
public function getIcon()
{
return $this->icon;
}
/**
* Return whether this menu has any sub menus
*
* @return bool
*/
public function hasSubMenus()
{
return false === empty($this->subMenus);
}
/**
* Add a sub menu to this menu
*
* @param string $id The id of the menu to add
* @param Zend_Config $itemConfig The config with which to initialize the menu
*
* @return self
*/
public function addSubMenu($id, Zend_Config $menuConfig = null)
{
if (false === ($pos = strpos($id, '.'))) {
$subMenu = new self($id, $menuConfig);
$this->subMenus[$id] = $subMenu;
} else {
list($parentId, $id) = explode('.', $id, 2);
if ($this->hasSubMenu($parentId)) {
$parent = $this->getSubMenu($parentId);
} else {
$parent = $this->addSubMenu($parentId);
}
$subMenu = $parent->addSubMenu($id, $menuConfig);
}
return $subMenu;
}
/**
* Return whether a sub menu with the given id exists
*
* @param string $id The id of the sub menu
*
* @return bool
*/
public function hasSubMenu($id)
{
return array_key_exists($id, $this->subMenus);
}
/**
* Get sub menu by its id
*
* @param string $id The id of the sub menu
*
* @return Menu The found sub menu
*
* @throws ProgrammingError In case there is no sub menu with the given id to be found
*/
public function getSubMenu($id)
{
if (false === $this->hasSubMenu($id)) {
throw new ProgrammingError('Tried to get invalid sub menu "' . $id . '"');
}
return $this->subMenus[$id];
}
/**
* Order this menu's sub menus based on their priority
*
* @return self
*/
public function order()
{
uasort($this->subMenus, array($this, 'cmpSubMenus'));
foreach ($this->subMenus as $subMenu) {
if ($subMenu->hasSubMenus()) {
$subMenu->order();
}
}
return $this;
}
/**
* Compare sub menus based on priority and title
*
* @param Menu $a
* @param Menu $b
*
* @return int
*/
protected function cmpSubMenus($a, $b)
{
if ($a->priority == $b->priority) {
return $a->getTitle() > $b->getTitle() ? 1 : (
$a->getTitle() < $b->getTitle() ? -1 : 0
);
}
return $a->priority > $b->priority ? 1 : -1;
}
/**
@ -83,7 +326,7 @@ class Menu extends MenuItem
*
* @return array The flattened config, as key-value array
*/
public function flattenConfigs(array $configs)
protected function flattenConfigs(array $configs)
{
$flattened = array();
foreach ($configs as $menuConfig) {
@ -99,18 +342,89 @@ class Menu extends MenuItem
}
/**
* Load menu items
* Load the sub menus
*
* @param array $items The items to load, as key-value array
* @param array $menus The menus to load, as key-value array
*
* @return self
*/
public function loadMenuItems(array $items)
protected function loadSubMenus(array $menus)
{
foreach ($items as $id => $itemConfig) {
$this->addChild($id, $itemConfig);
foreach ($menus as $menuId => $menuConfig) {
$this->addSubMenu($menuId, $menuConfig);
}
return $this;
}
/**
* Check whether the current menu node has any sub menus
*
* @return bool
*/
public function hasChildren()
{
$current = $this->current();
if (false !== $current) {
return $current->hasSubMenus();
}
return false;
}
/**
* Return a iterator for the current menu node
*
* @return RecursiveIterator
*/
public function getChildren()
{
return $this->current();
}
/**
* Rewind the iterator to its first menu node
*/
public function rewind()
{
reset($this->subMenus);
}
/**
* Return whether the iterator position is valid
*
* @return bool
*/
public function valid()
{
return $this->key() !== null;
}
/**
* Return the current menu node
*
* @return Menu
*/
public function current()
{
return current($this->subMenus);
}
/**
* Return the id of the current menu node
*
* @return string
*/
public function key()
{
return key($this->subMenus);
}
/**
* Move the iterator to the next menu node
*/
public function next()
{
next($this->subMenus);
}
}

View File

@ -1,361 +0,0 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Web;
use Icinga\Exception\ProgrammingError;
class MenuItem
{
/**
* Item id
*
* @type string
*/
protected $id;
/**
* Item title
*
* Used for sorting when priority is unset or equal to other items
*
* @type string
*/
protected $title;
/**
* Item priority
*
* Used for sorting
*
* @type int
*/
protected $priority = 100;
/**
* Item url
*
* @type string
*/
protected $url;
/**
* Item icon path
*
* @type string
*/
protected $icon;
/**
* Item icon class
*
* @type string
*/
protected $iconClass;
/**
* Item's children
*
* @type array
*/
protected $children = array();
/**
* HTML anchor tag attributes
*
* @var array
*/
protected $attribs = array();
/**
* Create a new MenuItem
*
* @param int $id
* @param object $config
*/
public function __construct($id, $config = null)
{
$this->id = $id;
if ($config !== null) {
$this->setConfig($config);
}
}
/**
* Setter for id
*
* @param string $id
*
* @return self
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Getter for id
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Setter for title
*
* @param string $title
*
* @return self
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Getter for title
*
* @return string
*/
public function getTitle()
{
return $this->title ? $this->title : $this->id;
}
/**
* Setter for priority
*
* @param int $priority
*
* @return self
*/
public function setPriority($priority)
{
$this->priority = (int) $priority;
return $this;
}
/**
* Getter for priority
*
* @return int
*/
public function getPriority()
{
return $this->priority;
}
/**
* Setter for URL
*
* @param string $url
*
* @return self
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Getter for URL
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Setter for icon path
*
* @param string $path
*
* @return self
*/
public function setIcon($path)
{
$this->icon = $path;
return $this;
}
/**
* Getter for icon path
*
* @return string
*/
public function getIcon()
{
return $this->icon;
}
/**
* Setter for icon class
*
* @param string $iconClass
*
* @return self
*/
public function setIconClass($iconClass)
{
$this->iconClass = $iconClass;
return $this;
}
/**
* Getter for icon class
*
* @return string
*/
public function getIconClass()
{
return $this->iconClass;
}
/**
* Set the configuration for the item
*
* @param Zend_Config $config
*/
public function setConfig($config)
{
foreach ($config as $key => $value) {
$method = 'set' . implode('', array_map('ucfirst', explode('_', strtolower($key))));
if (method_exists($this, $method)) {
$this->{$method}($value);
}
}
}
/**
* Add a child to MenuItem
*
* @param string $id
* @param object $itemConfig
*
* @return self
*/
public function addChild($id, $itemConfig = null)
{
if (false === ($pos = strpos($id, '.'))) {
// Root item
$menuItem = new self($id, $itemConfig);
$this->children[$id] = $menuItem;
} else {
// Submenu item
list($parentId, $id) = explode('.', $id, 2);
if ($this->hasChild($parentId)) {
$parent = $this->getChild($parentId);
} else {
$parent = $this->addChild($parentId);
}
$menuItem = $parent->addChild($id, $itemConfig);
}
return $menuItem;
}
/**
* Check whether the item has any children
*
* @return bool
*/
public function hasChildren()
{
return !empty($this->children);
}
/**
* Get sorted children
*
* @return array
*
* @see MenuItem::cmpChildren()
*/
public function getChildren()
{
usort($this->children, array($this, 'cmpChildren'));
return $this->children;
}
/**
* Return whether a given child id exists
*
* @param string $id
*
* @return bool
*/
public function hasChild($id)
{
return array_key_exists($id, $this->children);
}
/**
* Get child by its id
*
* @param string $id
* @param mixed $default
*
* @return MenuItem
*
* @throws ProgrammingError
*/
public function getChild($id)
{
if (!$this->hasChild($id)) {
throw new ProgrammingError(sprintf('Trying to get invalid Menu child "%s"', $id));
}
return $this->children[$id];
}
/**
* Set HTML anchor tag attributes
*
* @param array $attribs
*
* @return self
*/
public function setAttribs(array $attribs)
{
$this->attribs = $attribs;
return $this;
}
/**
* Get HTML anchor tag attributes
*
* @return array
*/
public function getAttribs()
{
return $this->attribs;
}
/**
* Compare children based on priority and title
*
* @param MenuItem $a
* @param MenuItem $b
*
* @return int
*/
protected function cmpChildren($a, $b)
{
if ($a->priority === $b->priority) {
return ($a->getTitle() > $b->getTitle()) ? 1 : -1;
}
return ($a->priority > $b->priority) ? 1 : -1;
}
}

View File

@ -0,0 +1,151 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Web;
use RecursiveIteratorIterator;
/**
* A renderer to draw a menu with its sub-menus using an unordered html list
*/
class MenuRenderer extends RecursiveIteratorIterator
{
/**
* The relative url of the current request
*
* @var string
*/
protected $url;
/**
* The html tags to assemble the menu with
*
* @var array
*/
protected $tags = array();
/**
* Create a new MenuRenderer
*
* @param Menu $menu The menu to render
* @param string $url A relative url to identify "active" children with
*/
public function __construct(Menu $menu, $url = null)
{
$this->url = $url;
parent::__construct($menu, RecursiveIteratorIterator::CHILD_FIRST);
}
/**
* Register the outer ul opening html-tag
*/
public function beginIteration()
{
$this->tags[] = '<ul role="navigation">';
}
/**
* Register the outer ul closing html-tag
*/
public function endIteration()
{
$this->tags[] = '</ul>';
}
/**
* Register a inner ul opening html-tag
*/
public function beginChildren()
{
// The iterator runs in mode CHILD_FIRST so we need to remember
// where to insert the parent's opening html tag once its rendered
$parent = $this->getSubIterator(0)->current();
$this->tags[$parent->getId() . '_begin'] = null;
$this->tags[] = '<ul>';
}
/**
* Register a inner ul closing html-tag
*/
public function endChildren()
{
$this->tags[] = '</ul>';
// Remember the position of the parent's closing html-tag
$parent = $this->getSubIterator(0)->current();
$this->tags[$parent->getId() . '_end'] = null;
}
/**
* Render the given child
*
* @param Menu $child The menu's child to render
*
* @return string The child rendered as html
*/
public function renderChild(Menu $child)
{
return sprintf(
'<a href="%s">%s%s</a>',
$child->getUrl() ? Url::fromPath($child->getUrl()) : '#',
$child->getIcon() ? '<img src="' . Url::fromPath($child->getIcon()) . '" class="icon" /> ' : '',
htmlspecialchars($child->getTitle())
);
}
/**
* Return the menu rendered as html
*
* @return string
*/
public function render()
{
$passedActiveChild = false;
foreach ($this as $child) {
$childIsActive = $this->isActive($child);
if ($childIsActive && $this->getDepth() > 0) {
$passedActiveChild = true;
}
if ($childIsActive || ($passedActiveChild && $this->getDepth() === 0)) {
$passedActiveChild &= $this->getDepth() !== 0;
$openTag = '<li class="active">';
} else {
$openTag = '<li>';
}
$content = $this->renderChild($child);
$closingTag = '</li>';
if (array_key_exists($child->getId() . '_begin', $this->tags)) {
$this->tags[$child->getId() . '_begin'] = $openTag . $content;
$this->tags[$child->getId() . '_end'] = $closingTag;
} else {
$this->tags[] = $openTag . $content . $closingTag;
}
}
return implode("\n", $this->tags);
}
/**
* @see MenuRenderer::render()
*/
public function __toString()
{
return $this->render();
}
/**
* Return whether the current request url references the child's url
*
* @param Menu $child The menu's child to check
*
* @return bool
*/
protected function isActive(Menu $child)
{
return html_entity_decode(rawurldecode($this->url)) === html_entity_decode(rawurldecode($child->getUrl()));
}
}

View File

@ -1,29 +0,0 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Tests\Icinga\Web;
use Zend_Config;
use Icinga\Web\MenuItem;
use Icinga\Test\BaseTestCase;
class MenuItemTest extends BaseTestCase
{
public function testWhetherMenuItemsAreNaturallySorted()
{
$item = new MenuItem('test');
$item->addChild(5, new Zend_Config(array('title' => 'ccc5')));
$item->addChild(0, new Zend_Config(array('title' => 'aaa')));
$item->addChild(3, new Zend_Config(array('title' => 'ccc')));
$item->addChild(2, new Zend_Config(array('title' => 'bbb')));
$item->addChild(4, new Zend_Config(array('title' => 'ccc2')));
$item->addChild(1, new Zend_Config(array('title' => 'bb')));
$this->assertEquals(
array('aaa', 'bb', 'bbb', 'ccc', 'ccc2', 'ccc5'),
array_map(function ($it) { return $it->getTitle(); }, $item->getChildren()),
'MenuItem::getChildren does not return its elements in natural order'
);
}
}

View File

@ -0,0 +1,29 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Tests\Icinga\Web;
use Zend_Config;
use Icinga\Web\Menu;
use Icinga\Test\BaseTestCase;
class MenuTest extends BaseTestCase
{
public function testWhetherMenusAreNaturallySorted()
{
$menu = new Menu('test');
$menu->addSubMenu(5, new Zend_Config(array('title' => 'ccc5')));
$menu->addSubMenu(0, new Zend_Config(array('title' => 'aaa')));
$menu->addSubMenu(3, new Zend_Config(array('title' => 'ccc')));
$menu->addSubMenu(2, new Zend_Config(array('title' => 'bbb')));
$menu->addSubMenu(4, new Zend_Config(array('title' => 'ccc2')));
$menu->addSubMenu(1, new Zend_Config(array('title' => 'bb')));
$this->assertEquals(
array('aaa', 'bb', 'bbb', 'ccc', 'ccc2', 'ccc5'),
array_map(function ($m) { return $m->getTitle(); }, iterator_to_array($menu->order())),
'Menu::order() does not return its elements in natural order'
);
}
}