Permalink
Browse files

fix(menus): stricter type validation in menu item registration functions

elgg_register_menu_item() and elgg_unregister_menu_item() now conform with the inline docs
and ensure that arguments are of valid type.
  • Loading branch information...
hypeJunction committed Dec 25, 2015
1 parent 4319ea4 commit c5554a75bb45acf9f27c13a8d58a0e099063cf26
Showing with 25 additions and 12 deletions.
  1. +16 −12 engine/lib/navigation.php
  2. +9 −0 engine/tests/phpunit/ElggMenuItemTest.php
View
@@ -92,21 +92,25 @@
function elgg_register_menu_item($menu_name, $menu_item) {
global $CONFIG;
if (!isset($CONFIG->menus[$menu_name])) {
$CONFIG->menus[$menu_name] = array();
}
if (is_array($menu_item)) {
$item = \ElggMenuItem::factory($menu_item);
if (!$item) {
elgg_log("Unable to add menu item '{$menu_item['name']}' to '$menu_name' menu", 'WARNING');
$options = $menu_item;
$menu_item = \ElggMenuItem::factory($options);
if (!$menu_item) {
$menu_item_name = elgg_extract('name', $options, 'MISSING NAME');
elgg_log("Unable to add menu item '{$menu_item_name}' to '$menu_name' menu", 'WARNING');
return false;
}
} else {
$item = $menu_item;
}
$CONFIG->menus[$menu_name][] = $item;
if (!$menu_item instanceof ElggMenuItem) {
elgg_log('Second argument of elgg_register_menu_item() must be an instance of ElggMenuItem or an array of menu item factory options', 'ERROR');
return false;
}
if (!isset($CONFIG->menus[$menu_name])) {
$CONFIG->menus[$menu_name] = array();
}
$CONFIG->menus[$menu_name][] = $menu_item;
return true;
}
@@ -122,13 +126,13 @@ function elgg_register_menu_item($menu_name, $menu_item) {
function elgg_unregister_menu_item($menu_name, $item_name) {
global $CONFIG;
if (!isset($CONFIG->menus[$menu_name])) {
if (empty($CONFIG->menus[$menu_name])) {
return null;
}
foreach ($CONFIG->menus[$menu_name] as $index => $menu_object) {
/* @var \ElggMenuItem $menu_object */
if ($menu_object->getName() == $item_name) {
if ($menu_object instanceof ElggMenuItem && $menu_object->getName() == $item_name) {
$item = $CONFIG->menus[$menu_name][$index];
unset($CONFIG->menus[$menu_name][$index]);
return $item;
@@ -195,4 +195,13 @@ public function testGetItemClassNormalizeName() {
$item = new \ElggMenuItem('name:colon', 'text', 'url');
$this->assertEquals('elgg-menu-item-name-colon', $item->getItemClass());
}
public function testArgumentTypeValidationOnItemRegistration() {
$this->assertTrue(elgg_register_menu_item('foo', new \ElggMenuItem('foo', 'bar', 'url')));
$this->assertTrue(elgg_register_menu_item('foo', array('name' => 'foo', 'text' => 'bar')));
$this->assertFalse(elgg_register_menu_item('foo', array()));
$this->assertFalse(elgg_register_menu_item('foo', array('text' => 'bar')));
$this->assertFalse(elgg_register_menu_item('foo', 'bar'));
$this->assertFalse(elgg_register_menu_item('foo', new stdClass()));
}
}

0 comments on commit c5554a7

Please sign in to comment.