MDL-82159 core: Coding style fixes for navigation

This commit is contained in:
Andrew Nicols
2025-07-30 23:34:15 +08:00
parent 1b7682d536
commit 090926c281
18 changed files with 1392 additions and 869 deletions
@@ -28,7 +28,6 @@ use core\exception\coding_exception;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class breadcrumb_navigation_node extends navigation_node {
/** @var $last boolean A flag indicating this is the last item in the list of breadcrumbs. */
private $last = false;
@@ -41,7 +40,6 @@ class breadcrumb_navigation_node extends navigation_node {
if (is_array($navnode)) {
parent::__construct($navnode);
} else if ($navnode instanceof navigation_node) {
// Just clone everything.
$objvalues = get_object_vars($navnode);
foreach ($objvalues as $key => $value) {
@@ -30,6 +30,10 @@ use moodle_page;
* @copyright 2016 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
#[\core\attribute\deprecated(
since: '4.0',
reason: 'Do not use this class any more. Leverage secondary/tertiary navigation concepts.'
)]
class flat_navigation extends navigation_node_collection {
/** @var moodle_page the moodle page that the navigation belongs to */
protected $page;
@@ -66,7 +70,7 @@ class flat_navigation extends navigation_node_collection {
// First walk the nav tree looking for "flat_navigation" nodes.
if ($course->id > 1) {
// It's a real course.
$url = new url('/course/view.php', array('id' => $course->id));
$url = new url('/course/view.php', ['id' => $course->id]);
$coursecontext = context_course::instance($course->id, MUST_EXIST);
$displaycontext = context_helper::get_navigation_filter_context($coursecontext);
@@ -123,9 +127,11 @@ class flat_navigation extends navigation_node_collection {
}
// Add-a-block in editing mode.
if (isset($this->page->theme->addblockposition) &&
if (
isset($this->page->theme->addblockposition) &&
$this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
$PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()) {
$PAGE->user_is_editing() && $PAGE->user_can_edit_blocks()
) {
$url = new url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
$addablock = navigation_node::create(get_string('addblock'), $url);
$flat = new flat_navigation_node($addablock, 0);
@@ -136,8 +142,11 @@ class flat_navigation extends navigation_node_collection {
$addblockurl = "?{$url->get_query_string(false)}";
$PAGE->requires->js_call_amd('core_block/add_modal', 'init',
[$addblockurl, $this->page->get_edited_page_hash()]);
$PAGE->requires->js_call_amd(
'core_block/add_modal',
'init',
[$addblockurl, $this->page->get_edited_page_hash()]
);
}
}
@@ -149,7 +158,7 @@ class flat_navigation extends navigation_node_collection {
* otherwise adds at end
* @return navigation_node Added node
*/
public function add(navigation_node $node, $beforekey=null) {
public function add(navigation_node $node, $beforekey = null) {
$result = parent::add($node, $beforekey);
// Extend the parent to get a name for the collection of nodes if required.
if (empty($this->collectionlabel)) {
@@ -29,7 +29,6 @@ use core\exception\coding_exception;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class flat_navigation_node extends navigation_node {
/** @var $indent integer The indent level */
private $indent = 0;
@@ -49,7 +48,6 @@ class flat_navigation_node extends navigation_node {
if (is_array($navnode)) {
parent::__construct($navnode);
} else if ($navnode instanceof navigation_node) {
// Just clone everything.
$objvalues = get_object_vars($navnode);
foreach ($objvalues as $key => $value) {
File diff suppressed because it is too large Load Diff
@@ -38,7 +38,6 @@ use moodle_page;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class global_navigation_for_ajax extends global_navigation {
/** @var int used for determining what type of navigation_node::TYPE_* is being used */
protected $branchtype;
@@ -46,7 +45,7 @@ class global_navigation_for_ajax extends global_navigation {
protected $instanceid;
/** @var array Holds an array of expandable nodes */
protected $expandable = array();
protected $expandable = [];
/**
* Constructs the navigation for use in an AJAX request
@@ -63,11 +62,8 @@ class global_navigation_for_ajax extends global_navigation {
$this->instanceid = $id;
$this->initialise();
}
/**
* Initialise the navigation given the type and id for the branch to expand.
*
* @return array An array of the expandable nodes
*/
#[\Override]
public function initialise() {
global $DB, $SITE;
@@ -76,7 +72,7 @@ class global_navigation_for_ajax extends global_navigation {
}
$this->initialised = true;
$this->rootnodes = array();
$this->rootnodes = [];
$this->rootnodes['site'] = $this->add_course($SITE);
$this->rootnodes['mycourses'] = $this->add(
get_string('mycourses'),
@@ -90,7 +86,7 @@ class global_navigation_for_ajax extends global_navigation {
// This mimicks what is done during {@link global_navigation::initialise()}.
$this->rootnodes['courses']->isexpandable = true;
// Branchtype will be one of navigation_node::TYPE_*
// Branchtype will be one of navigation_node::TYPE_*.
switch ($this->branchtype) {
case 0:
if ($this->instanceid === 'mycourses') {
@@ -99,14 +95,14 @@ class global_navigation_for_ajax extends global_navigation {
$this->load_courses_other();
}
break;
case self::TYPE_CATEGORY :
case self::TYPE_CATEGORY:
$this->load_category($this->instanceid);
break;
case self::TYPE_MY_CATEGORY :
case self::TYPE_MY_CATEGORY:
$this->load_category($this->instanceid, self::TYPE_MY_CATEGORY);
break;
case self::TYPE_COURSE :
$course = $DB->get_record('course', array('id' => $this->instanceid), '*', MUST_EXIST);
case self::TYPE_COURSE:
$course = $DB->get_record('course', ['id' => $this->instanceid], '*', MUST_EXIST);
if (!can_access_course($course, null, '', true)) {
// Thats OK all courses are expandable by default. We don't need to actually expand it we can just
// add the course node and break. This leads to an empty node.
@@ -119,24 +115,24 @@ class global_navigation_for_ajax extends global_navigation {
$this->add_course_essentials($coursenode, $course);
$this->load_course_sections($course, $coursenode);
break;
case self::TYPE_SECTION :
case self::TYPE_SECTION:
$sql = 'SELECT c.*, cs.section AS sectionnumber
FROM {course} c
LEFT JOIN {course_sections} cs ON cs.course = c.id
WHERE cs.id = ?';
$course = $DB->get_record_sql($sql, array($this->instanceid), MUST_EXIST);
$course = $DB->get_record_sql($sql, [$this->instanceid], MUST_EXIST);
require_course_login($course, true, null, false, true);
$this->page->set_context(context_course::instance($course->id));
$coursenode = $this->add_course($course, false, self::COURSE_CURRENT);
$this->add_course_essentials($coursenode, $course);
$this->load_course_sections($course, $coursenode, $course->sectionnumber);
break;
case self::TYPE_ACTIVITY :
case self::TYPE_ACTIVITY:
$sql = "SELECT c.*
FROM {course} c
JOIN {course_modules} cm ON cm.course = c.id
WHERE cm.id = :cmid";
$params = array('cmid' => $this->instanceid);
$params = ['cmid' => $this->instanceid];
$course = $DB->get_record_sql($sql, $params, MUST_EXIST);
$modinfo = get_fast_modinfo($course);
$cm = $modinfo->get_cm($this->instanceid);
@@ -195,13 +191,13 @@ class global_navigation_for_ajax extends global_navigation {
$sql = "SELECT cc.*, $catcontextsql
FROM {course_categories} cc
JOIN {context} ctx ON cc.id = ctx.instanceid
WHERE ctx.contextlevel = ".CONTEXT_COURSECAT." AND
WHERE ctx.contextlevel = " . CONTEXT_COURSECAT . " AND
(cc.id = :categoryid1 OR cc.parent = :categoryid2)
ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC";
$params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid);
$params = ['categoryid1' => $categoryid, 'categoryid2' => $categoryid];
$categories = $DB->get_recordset_sql($sql, $params, 0, $limit);
$categorylist = array();
$subcategories = array();
$categorylist = [];
$subcategories = [];
$basecategory = null;
foreach ($categories as $category) {
$categorylist[] = $category->id;
@@ -215,12 +211,11 @@ class global_navigation_for_ajax extends global_navigation {
}
$categories->close();
// If category is shown in MyHome then only show enrolled courses and hide empty subcategories,
// else show all courses.
if ($nodetype === self::TYPE_MY_CATEGORY) {
$courses = enrol_get_my_courses('*');
$categoryids = array();
$categoryids = [];
// Only search for categories if basecategory was found.
if (!is_null($basecategory)) {
@@ -231,13 +226,13 @@ class global_navigation_for_ajax extends global_navigation {
// Get a unique list of category ids which a part of the path
// to user's courses.
$coursesubcategories = array();
$addedsubcategories = array();
$coursesubcategories = [];
$addedsubcategories = [];
list($sql, $params) = $DB->get_in_or_equal($categoryids);
$categories = $DB->get_recordset_select('course_categories', 'id '.$sql, $params, 'sortorder, id', 'id, path');
[$sql, $params] = $DB->get_in_or_equal($categoryids);
$categories = $DB->get_recordset_select('course_categories', 'id ' . $sql, $params, 'sortorder, id', 'id, path');
foreach ($categories as $category){
foreach ($categories as $category) {
$coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/")));
}
$categories->close();
@@ -246,8 +241,10 @@ class global_navigation_for_ajax extends global_navigation {
// Only add a subcategory if it is part of the path to user's course and
// wasn't already added.
foreach ($subcategories as $subid => $subcategory) {
if (in_array($subid, $coursesubcategories) &&
!in_array($subid, $addedsubcategories)) {
if (
in_array($subid, $coursesubcategories) &&
!in_array($subid, $addedsubcategories)
) {
$this->add_category($subcategory, $basecategory, $nodetype);
$addedsubcategories[] = $subid;
}
@@ -262,11 +259,11 @@ class global_navigation_for_ajax extends global_navigation {
}
} else {
if (!is_null($basecategory)) {
foreach ($subcategories as $key=>$category) {
foreach ($subcategories as $key => $category) {
$this->add_category($category, $basecategory, $nodetype);
}
}
$courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*' , 0, $limit);
$courses = $DB->get_recordset('course', ['category' => $categoryid], 'sortorder', '*', 0, $limit);
foreach ($courses as $course) {
$this->add_course($course);
}
@@ -275,7 +272,8 @@ class global_navigation_for_ajax extends global_navigation {
}
/**
* Returns an array of expandable nodes
* Returns an array of expandable nodes.
*
* @return array
*/
public function get_expandable() {
+61 -49
View File
@@ -40,7 +40,7 @@ class navbar extends navigation_node {
/** @var bool A switch for whether the navbar is initialised or not */
protected $initialised = false;
/** @var mixed keys used to reference the nodes on the navbar */
protected $keys = array();
protected $keys = [];
/** @var null|string content of the navbar */
protected $content = null;
/** @var moodle_page object the moodle page that this navbar belongs to */
@@ -54,11 +54,11 @@ class navbar extends navigation_node {
/** @var array An array of navigation nodes for the navbar */
protected $items;
/** @var array An array of child node objects */
public $children = array();
public $children = [];
/** @var bool A switch for whether we want to include the root node in the navbar */
public $includesettingsbase = false;
/** @var breadcrumb_navigation_node[] $prependchildren */
protected $prependchildren = array();
protected $prependchildren = [];
/**
* The almighty constructor
@@ -71,10 +71,11 @@ class navbar extends navigation_node {
$this->duringinstall = true;
return;
}
$this->page = $page;
$this->text = get_string('home');
$this->shorttext = get_string('home');
$this->action = new moodle_url($CFG->wwwroot);
$this->action = new url($CFG->wwwroot);
$this->nodetype = self::NODETYPE_BRANCH;
$this->type = self::TYPE_SYSTEM;
}
@@ -108,7 +109,7 @@ class navbar extends navigation_node {
*
* @param bool $setting
*/
public function ignore_active($setting=true) {
public function ignore_active($setting = true) {
$this->ignoreactive = ($setting);
}
@@ -139,8 +140,8 @@ class navbar extends navigation_node {
*/
public function get_items() {
global $CFG;
$items = array();
// Make sure that navigation is initialised
$items = [];
// Make sure that navigation is initialised.
if (!$this->has_items()) {
return $items;
}
@@ -153,7 +154,7 @@ class navbar extends navigation_node {
$items = array_reverse($this->children);
}
// Check if navigation contains the active node
// Check if navigation contains the active node.
if (!$this->ignoreactive) {
// We will need to ensure the navigation has been initialised.
$this->page->navigation->initialise($this->page);
@@ -162,7 +163,7 @@ class navbar extends navigation_node {
$settingsactivenode = $this->page->settingsnav->find_active_node();
if ($navigationactivenode && $settingsactivenode) {
// Parse a combined navigation tree
// Parse a combined navigation tree.
while ($settingsactivenode && $settingsactivenode->parent !== null) {
if (!$settingsactivenode->mainnavonly) {
$items[] = new breadcrumb_navigation_node($settingsactivenode);
@@ -170,16 +171,18 @@ class navbar extends navigation_node {
$settingsactivenode = $settingsactivenode->parent;
}
if (!$this->includesettingsbase) {
// Removes the first node from the settings (root node) from the list
// Removes the first node from the settings (root node) from the list.
array_pop($items);
}
while ($navigationactivenode && $navigationactivenode->parent !== null) {
if (!$navigationactivenode->mainnavonly) {
$items[] = new breadcrumb_navigation_node($navigationactivenode);
}
if (!empty($CFG->navshowcategories) &&
if (
!empty($CFG->navshowcategories) &&
$navigationactivenode->type === self::TYPE_COURSE &&
$navigationactivenode->parent->key === 'currentcourse') {
$navigationactivenode->parent->key === 'currentcourse'
) {
foreach ($this->get_course_categories() as $item) {
$items[] = new breadcrumb_navigation_node($item);
}
@@ -187,14 +190,16 @@ class navbar extends navigation_node {
$navigationactivenode = $navigationactivenode->parent;
}
} else if ($navigationactivenode) {
// Parse the navigation tree to get the active node
// Parse the navigation tree to get the active node.
while ($navigationactivenode && $navigationactivenode->parent !== null) {
if (!$navigationactivenode->mainnavonly) {
$items[] = new breadcrumb_navigation_node($navigationactivenode);
}
if (!empty($CFG->navshowcategories) &&
if (
!empty($CFG->navshowcategories) &&
$navigationactivenode->type === self::TYPE_COURSE &&
$navigationactivenode->parent->key === 'currentcourse') {
$navigationactivenode->parent->key === 'currentcourse'
) {
foreach ($this->get_course_categories() as $item) {
$items[] = new breadcrumb_navigation_node($item);
}
@@ -202,7 +207,7 @@ class navbar extends navigation_node {
$navigationactivenode = $navigationactivenode->parent;
}
} else if ($settingsactivenode) {
// Parse the settings navigation to get the active node
// Parse the settings navigation to get the active node.
while ($settingsactivenode && $settingsactivenode->parent !== null) {
if (!$settingsactivenode->mainnavonly) {
$items[] = new breadcrumb_navigation_node($settingsactivenode);
@@ -212,15 +217,15 @@ class navbar extends navigation_node {
}
}
$items[] = new breadcrumb_navigation_node(array(
$items[] = new breadcrumb_navigation_node([
'text' => $this->page->navigation->text,
'shorttext' => $this->page->navigation->shorttext,
'key' => $this->page->navigation->key,
'action' => $this->page->navigation->action
));
'action' => $this->page->navigation->action,
]);
if (count($this->prependchildren) > 0) {
// Add the custom children
// Add the custom children.
$items = array_merge($items, array_reverse($this->prependchildren));
}
@@ -243,9 +248,9 @@ class navbar extends navigation_node {
*/
private function get_course_categories() {
global $CFG;
require_once($CFG->dirroot.'/course/lib.php');
require_once($CFG->dirroot . '/course/lib.php');
$categories = array();
$categories = [];
$cap = 'moodle/category:viewhiddencategories';
$showcategories = !core_course_category::is_simple_site();
@@ -256,8 +261,8 @@ class navbar extends navigation_node {
continue;
}
$displaycontext = \context_helper::get_navigation_filter_context($context);
$url = new moodle_url('/course/index.php', ['categoryid' => $category->id]);
$displaycontext = context_helper::get_navigation_filter_context($context);
$url = new url('/course/index.php', ['categoryid' => $category->id]);
$name = format_string($category->name, true, ['context' => $displaycontext]);
$categorynode = breadcrumb_navigation_node::create($name, $url, self::TYPE_CATEGORY, null, $category->id);
if (!$category->visible) {
@@ -275,7 +280,7 @@ class navbar extends navigation_node {
// Courses node may not be present.
$courses = breadcrumb_navigation_node::create(
get_string('courses'),
new moodle_url('/course/index.php'),
new url('/course/index.php'),
self::TYPE_CONTAINER
);
}
@@ -293,44 +298,44 @@ class navbar extends navigation_node {
* end of the navbar
*
* @param string $text
* @param string|moodle_url|action_link $action An action to associate with this node.
* @param string|url|action_link $action An action to associate with this node.
* @param int $type One of navigation_node::TYPE_*
* @param string $shorttext
* @param string|int $key A key to identify this node with. Key + type is unique to a parent.
* @param pix_icon $icon An optional icon to use for this node.
* @return navigation_node
*/
public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) {
public function add($text, $action = null, $type = self::TYPE_CUSTOM, $shorttext = null, $key = null, ?pix_icon $icon = null) {
if ($this->content !== null) {
debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
}
// Properties array used when creating the new navigation node
$itemarray = array(
// Properties array used when creating the new navigation node.
$itemarray = [
'text' => $text,
'type' => $type
);
// Set the action if one was provided
if ($action!==null) {
'type' => $type,
];
// Set the action if one was provided.
if ($action !== null) {
$itemarray['action'] = $action;
}
// Set the shorttext if one was provided
if ($shorttext!==null) {
// Set the shorttext if one was provided.
if ($shorttext !== null) {
$itemarray['shorttext'] = $shorttext;
}
// Set the icon if one was provided
if ($icon!==null) {
// Set the icon if one was provided.
if ($icon !== null) {
$itemarray['icon'] = $icon;
}
// Default the key to the number of children if not provided
// Default the key to the number of children if not provided.
if ($key === null) {
$key = count($this->children);
}
// Set the key
// Set the key.
$itemarray['key'] = $key;
// Set the parent to this node
// Set the parent to this node.
$itemarray['parent'] = $this;
// Add the child using the navigation_node_collections add method
// Add the child using the navigation_node_collections add method.
$this->children[] = new breadcrumb_navigation_node($itemarray);
return $this;
}
@@ -339,32 +344,39 @@ class navbar extends navigation_node {
* Prepends a new navigation_node to the start of the navbar
*
* @param string $text
* @param string|moodle_url|action_link $action An action to associate with this node.
* @param string|url|action_link $action An action to associate with this node.
* @param int $type One of navigation_node::TYPE_*
* @param string $shorttext
* @param string|int $key A key to identify this node with. Key + type is unique to a parent.
* @param pix_icon $icon An optional icon to use for this node.
* @return navigation_node
*/
public function prepend($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) {
public function prepend(
$text,
$action = null,
$type = self::TYPE_CUSTOM,
$shorttext = null,
$key = null,
?pix_icon $icon = null,
) {
if ($this->content !== null) {
debugging('Nav bar items must be printed before $OUTPUT->header() has been called', DEBUG_DEVELOPER);
}
// Properties array used when creating the new navigation node.
$itemarray = array(
$itemarray = [
'text' => $text,
'type' => $type
);
'type' => $type,
];
// Set the action if one was provided.
if ($action!==null) {
if ($action !== null) {
$itemarray['action'] = $action;
}
// Set the shorttext if one was provided.
if ($shorttext!==null) {
if ($shorttext !== null) {
$itemarray['shorttext'] = $shorttext;
}
// Set the icon if one was provided.
if ($icon!==null) {
if ($icon !== null) {
$itemarray['icon'] = $icon;
}
// Default the key to the number of children if not provided.
@@ -20,13 +20,6 @@ use core_cache\cache;
use core_cache\session_cache;
use core_shutdown_manager;
/**
* Class navigation_cache
*
* @package core
* @copyright 2025 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* The navigation_cache class is used for global and settings navigation data.
*
@@ -59,12 +52,12 @@ class navigation_cache {
protected $area;
/** @var int cache time information */
#[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')]
const CACHETIME = 0;
public const CACHETIME = 0;
/** @var int cache user id */
#[\core\attribute\deprecated(null, since: '4.5', reason: 'This constant is no longer needed.', mdl: 'MDL-79628')]
const CACHEUSERID = 1;
public const CACHEUSERID = 1;
/** @var int cache value */
const CACHEVALUE = 2;
public const CACHEVALUE = 2;
/** @var null|array An array of cache areas to expire on shutdown */
public static $volatilecaches = null;
@@ -30,9 +30,9 @@ use core\url;
*/
class navigation_json {
/** @var array An array of different node types */
protected $nodetype = array('node','branch');
protected $nodetype = ['node', 'branch'];
/** @var array An array of node keys and types */
protected $expandable = array();
protected $expandable = [];
/**
* Turns a branch and all of its children into XML
*
@@ -50,7 +50,7 @@ class navigation_json {
*/
public function set_expandable($expandable) {
foreach ($expandable as $node) {
$this->expandable[$node['key'].':'.$node['type']] = $node;
$this->expandable[$node['key'] . ':' . $node['type']] = $node;
}
}
/**
@@ -60,11 +60,11 @@ class navigation_json {
* @param int $depth Pointlessly used to track the depth of the XML structure
* @return string JSON
*/
protected function convert_child($child, $depth=1) {
protected function convert_child($child, $depth = 1) {
if (!$child->display) {
return '';
}
$attributes = array();
$attributes = [];
$attributes['id'] = $child->id;
$attributes['name'] = (string)$child->text; // This can be lang_string object so typecast it.
$attributes['type'] = $child->type;
@@ -73,17 +73,16 @@ class navigation_json {
$attributes['requiresajaxloading'] = $child->requiresajaxloading;
if ($child->icon instanceof pix_icon) {
$attributes['icon'] = array(
$attributes['icon'] = [
'component' => $child->icon->component,
'pix' => $child->icon->pix,
);
foreach ($child->icon->attributes as $key=>$value) {
];
foreach ($child->icon->attributes as $key => $value) {
if ($key == 'class') {
$attributes['icon']['classes'] = explode(' ', $value);
} else if (!array_key_exists($key, $attributes['icon'])) {
$attributes['icon'][$key] = $value;
}
}
} else if (!empty($child->icon)) {
$attributes['icon'] = (string)$child->icon;
@@ -92,13 +91,13 @@ class navigation_json {
if ($child->forcetitle || $child->title !== $child->text) {
$attributes['title'] = htmlentities($child->title ?? '', ENT_QUOTES, 'UTF-8');
}
if (array_key_exists($child->key.':'.$child->type, $this->expandable)) {
if (array_key_exists($child->key . ':' . $child->type, $this->expandable)) {
$attributes['expandable'] = $child->key;
$child->add_class($this->expandable[$child->key.':'.$child->type]['id']);
$child->add_class($this->expandable[$child->key . ':' . $child->type]['id']);
}
if (count($child->classes)>0) {
$attributes['class'] .= ' '.join(' ',$child->classes);
if (count($child->classes) > 0) {
$attributes['class'] .= ' ' . join(' ', $child->classes);
}
if (is_string($child->action)) {
$attributes['link'] = $child->action;
@@ -108,13 +107,13 @@ class navigation_json {
$attributes['link'] = $child->action->url->out();
}
$attributes['hidden'] = ($child->hidden);
$attributes['haschildren'] = ($child->children->count()>0 || $child->type == navigation_node::TYPE_CATEGORY);
$attributes['haschildren'] = ($child->children->count() > 0 || $child->type == navigation_node::TYPE_CATEGORY);
$attributes['haschildren'] = $attributes['haschildren'] || $child->type == navigation_node::TYPE_MY_CATEGORY;
if ($child->children->count() > 0) {
$attributes['children'] = array();
$attributes['children'] = [];
foreach ($child->children as $subchild) {
$attributes['children'][] = $this->convert_child($subchild, $depth+1);
$attributes['children'][] = $this->convert_child($subchild, $depth + 1);
}
}
+124 -110
View File
@@ -40,45 +40,45 @@ use core\url;
*/
class navigation_node implements renderable {
/** @var int Used to identify this node a leaf (default) 0 */
const NODETYPE_LEAF = 0;
public const NODETYPE_LEAF = 0;
/** @var int Used to identify this node a branch, happens with children 1 */
const NODETYPE_BRANCH = 1;
public const NODETYPE_BRANCH = 1;
/** @var null Unknown node type null */
const TYPE_UNKNOWN = null;
public const TYPE_UNKNOWN = null;
/** @var int System node type 0 */
const TYPE_ROOTNODE = 0;
public const TYPE_ROOTNODE = 0;
/** @var int System node type 1 */
const TYPE_SYSTEM = 1;
public const TYPE_SYSTEM = 1;
/** @var int Category node type 10 */
const TYPE_CATEGORY = 10;
public const TYPE_CATEGORY = 10;
/** var int Category displayed in MyHome navigation node */
const TYPE_MY_CATEGORY = 11;
public const TYPE_MY_CATEGORY = 11;
/** @var int Course node type 20 */
const TYPE_COURSE = 20;
public const TYPE_COURSE = 20;
/** @var int Course Structure node type 30 */
const TYPE_SECTION = 30;
public const TYPE_SECTION = 30;
/** @var int Activity node type, e.g. Forum, Quiz 40 */
const TYPE_ACTIVITY = 40;
public const TYPE_ACTIVITY = 40;
/** @var int Resource node type, e.g. Link to a file, or label 50 */
const TYPE_RESOURCE = 50;
public const TYPE_RESOURCE = 50;
/** @var int A custom node type, default when adding without specifing type 60 */
const TYPE_CUSTOM = 60;
public const TYPE_CUSTOM = 60;
/** @var int Setting node type, used only within settings nav 70 */
const TYPE_SETTING = 70;
public const TYPE_SETTING = 70;
/** @var int site admin branch node type, used only within settings nav 71 */
const TYPE_SITE_ADMIN = 71;
public const TYPE_SITE_ADMIN = 71;
/** @var int Setting node type, used only within settings nav 80 */
const TYPE_USER = 80;
public const TYPE_USER = 80;
/** @var int Setting node type, used for containers of no importance 90 */
const TYPE_CONTAINER = 90;
public const TYPE_CONTAINER = 90;
/** var int Course the current user is not enrolled in */
const COURSE_OTHER = 0;
public const COURSE_OTHER = 0;
/** var int Course the current user is enrolled in but not viewing */
const COURSE_MY = 1;
public const COURSE_MY = 1;
/** var int Course the current user is currently viewing */
const COURSE_CURRENT = 2;
public const COURSE_CURRENT = 2;
/** var string The course index page navigation node */
const COURSE_INDEX_PAGE = 'courseindexpage';
public const COURSE_INDEX_PAGE = 'courseindexpage';
/** @var int Parameter to aid the coder in tracking [optional] */
public $id = null;
@@ -92,7 +92,7 @@ class navigation_node implements renderable {
public $title = null;
/** @var string A string that can be used to build a help button */
public $helpbutton = null;
/** @var moodle_url|action_link|null An action for the node (link) */
/** @var url|action_link|null An action for the node (link) */
public $action = null;
/** @var pix_icon The path to an icon to use for this node */
public $icon = null;
@@ -105,11 +105,11 @@ class navigation_node implements renderable {
/** @var bool If set to true the node will be expanded by default */
public $forceopen = false;
/** @var array An array of CSS classes for the node */
public $classes = array();
public $classes = [];
/** @var array An array of HTML attributes for the node */
public $attributes = [];
/** @var navigation_node_collection An array of child nodes */
public $children = array();
public $children = [];
/** @var bool If set to true the node will be recognised as active */
public $isactive = false;
/** @var bool If set to true the node will be dimmed */
@@ -129,10 +129,10 @@ class navigation_node implements renderable {
/** @var bool Set to true if we KNOW that this node can be expanded. */
public $isexpandable = false;
/** @var array */
protected $namedtypes = array(0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
protected $namedtypes = [0 => 'system', 10 => 'category', 20 => 'course', 30 => 'structure', 40 => 'activity',
50 => 'resource', 60 => 'custom', 70 => 'setting', 71 => 'siteadmin', 80 => 'user',
90 => 'container');
/** @var moodle_url */
90 => 'container'];
/** @var url */
protected static $fullmeurl = null;
/** @var bool toogles auto matching of active node */
public static $autofindactive = true;
@@ -166,13 +166,13 @@ class navigation_node implements renderable {
public function __construct($properties) {
if (is_array($properties)) {
// Check the array for each property that we allow to set at construction.
// text - The main content for the node
// shorttext - A short text if required for the node
// icon - The icon to display for the node
// type - The type of the node
// key - The key to use to identify the node
// parent - A reference to the nodes parent
// action - The action to attribute to this node, usually a URL to link to
// text - The main content for the node.
// shorttext - A short text if required for the node.
// icon - The icon to display for the node.
// type - The type of the node.
// key - The key to use to identify the node.
// parent - A reference to the nodes parent.
// action - The action to attribute to this node, usually a URL to link to.
if (array_key_exists('text', $properties)) {
$this->text = $properties['text'];
}
@@ -198,11 +198,12 @@ class navigation_node implements renderable {
if (array_key_exists('key', $properties)) {
$this->key = $properties['key'];
}
// This needs to happen last because of the check_if_active call that occurs
// This needs to happen last because of the check_if_active call that occurs.
if (array_key_exists('action', $properties)) {
$this->action = $properties['action'];
if (is_string($this->action)) {
$this->action = new moodle_url($this->action);
$this->action = new url($this->action);
}
if (self::$autofindactive) {
$this->check_if_active();
@@ -217,7 +218,7 @@ class navigation_node implements renderable {
if ($this->text === null) {
throw new coding_exception('You must set the text for the node when you create it.');
}
// Instantiate a new navigation node collection for this nodes children
// Instantiate a new navigation node collection for this nodes children.
$this->children = new navigation_node_collection();
}
@@ -230,19 +231,20 @@ class navigation_node implements renderable {
* @param int $strength One of URL_MATCH_EXACT, URL_MATCH_PARAMS, or URL_MATCH_BASE
* @return bool
*/
public function check_if_active($strength=URL_MATCH_EXACT) {
public function check_if_active($strength = URL_MATCH_EXACT) {
global $FULLME, $PAGE;
// Set fullmeurl if it hasn't already been set
// Set fullmeurl if it hasn't already been set.
if (self::$fullmeurl == null) {
if ($PAGE->has_set_url()) {
self::override_active_url(new moodle_url($PAGE->url));
self::override_active_url(new url($PAGE->url));
} else {
self::override_active_url(new moodle_url($FULLME));
self::override_active_url(new url($FULLME));
}
}
// Compare the action of this node against the fullmeurl
if ($this->action instanceof moodle_url && $this->action->compare(self::$fullmeurl, $strength)) {
// Compare the action of this node against the fullmeurl.
if ($this->action instanceof url && $this->action->compare(self::$fullmeurl, $strength)) {
$this->make_active();
return true;
}
@@ -288,18 +290,17 @@ class navigation_node implements renderable {
}
/**
* This sets the URL that the URL of new nodes get compared to when locating
* the active node.
* This sets the URL that the URL of new nodes get compared to when locating the active node.
*
* The active node is the node that matches the URL set here. By default this
* is either $PAGE->url or if that hasn't been set $FULLME.
*
* @param moodle_url $url The url to use for the fullmeurl.
* @param url $url The url to use for the fullmeurl.
* @param bool $loadadmintree use true if the URL point to administration tree
*/
public static function override_active_url(moodle_url $url, $loadadmintree = false) {
public static function override_active_url(url $url, $loadadmintree = false) {
// Clone the URL, in case the calling script changes their URL later.
self::$fullmeurl = new moodle_url($url);
self::$fullmeurl = new url($url);
// True means we do not want AJAX loaded admin tree, required for all admin pages.
if ($loadadmintree) {
// Do not change back to false if already set.
@@ -308,6 +309,8 @@ class navigation_node implements renderable {
}
/**
* Require the admin tree.
*
* Use when page is linked from the admin tree,
* if not used navigation could not find the page using current URL
* because the tree is not fully loaded.
@@ -317,43 +320,53 @@ class navigation_node implements renderable {
}
/**
* Creates a navigation node, ready to add it as a child using add_node
* function. (The created node needs to be added before you can use it.)
* Creates a navigation node, ready to add it as a child using add_node function.
*
* The created node needs to be added before you can use it.
*
* @param string $text
* @param moodle_url|action_link $action
* @param url|action_link $action
* @param int $type
* @param string $shorttext
* @param string|int $key
* @param pix_icon $icon
* @return navigation_node
*/
public static function create($text, $action=null, $type=self::TYPE_CUSTOM,
$shorttext=null, $key=null, ?pix_icon $icon=null) {
if ($action && !($action instanceof moodle_url || $action instanceof action_link)) {
public static function create(
$text,
$action = null,
$type = self::TYPE_CUSTOM,
$shorttext = null,
$key = null,
?pix_icon $icon = null
) {
if ($action && !($action instanceof url || $action instanceof action_link)) {
debugging(
"It is required that the action provided be either an action_url|moodle_url." .
" Please update your definition.", E_NOTICE);
"It is required that the action provided be either an action_url|url." .
" Please update your definition.",
E_NOTICE
);
}
// Properties array used when creating the new navigation node
$itemarray = array(
// Properties array used when creating the new navigation node.
$itemarray = [
'text' => $text,
'type' => $type
);
// Set the action if one was provided
if ($action!==null) {
'type' => $type,
];
// Set the action if one was provided.
if ($action !== null) {
$itemarray['action'] = $action;
}
// Set the shorttext if one was provided
if ($shorttext!==null) {
// Set the shorttext if one was provided.
if ($shorttext !== null) {
$itemarray['shorttext'] = $shorttext;
}
// Set the icon if one was provided
if ($icon!==null) {
// Set the icon if one was provided.
if ($icon !== null) {
$itemarray['icon'] = $icon;
}
// Set the key
// Set the key.
$itemarray['key'] = $key;
// Construct and return
// Construct and return.
return new navigation_node($itemarray);
}
@@ -361,21 +374,21 @@ class navigation_node implements renderable {
* Adds a navigation node as a child of this node.
*
* @param string $text
* @param moodle_url|action_link|string $action
* @param url|action_link|string $action
* @param ?int $type
* @param string $shorttext
* @param string|int $key
* @param pix_icon $icon
* @return navigation_node
*/
public function add($text, $action=null, $type=self::TYPE_CUSTOM, $shorttext=null, $key=null, ?pix_icon $icon=null) {
public function add($text, $action = null, $type = self::TYPE_CUSTOM, $shorttext = null, $key = null, ?pix_icon $icon = null) {
if ($action && is_string($action)) {
$action = new moodle_url($action);
$action = new url($action);
}
// Create child node
// Create child node.
$childnode = self::create($text, $action, $type, $shorttext, $key, $icon);
// Add the child to end and return
// Add the child to end and return.
return $this->add_node($childnode);
}
@@ -386,34 +399,36 @@ class navigation_node implements renderable {
* @param string $beforekey
* @return navigation_node The added node
*/
public function add_node(navigation_node $childnode, $beforekey=null) {
// First convert the nodetype for this node to a branch as it will now have children
public function add_node(navigation_node $childnode, $beforekey = null) {
// First convert the nodetype for this node to a branch as it will now have children.
if ($this->nodetype !== self::NODETYPE_BRANCH) {
$this->nodetype = self::NODETYPE_BRANCH;
}
// Set the parent to this node
// Set the parent to this node.
$childnode->set_parent($this);
// Default the key to the number of children if not provided
// Default the key to the number of children if not provided.
if ($childnode->key === null) {
$childnode->key = $this->children->count();
}
// Add the child using the navigation_node_collections add method
// Add the child using the navigation_node_collections add method.
$node = $this->children->add($childnode, $beforekey);
// If added node is a category node or the user is logged in and it's a course
// then mark added node as a branch (makes it expandable by AJAX)
// then mark added node as a branch (makes it expandable by AJAX).
$type = $childnode->type;
if (($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
($type === self::TYPE_SITE_ADMIN)) {
if (
($type == self::TYPE_CATEGORY) || (isloggedin() && ($type == self::TYPE_COURSE)) || ($type == self::TYPE_MY_CATEGORY) ||
($type === self::TYPE_SITE_ADMIN)
) {
$node->nodetype = self::NODETYPE_BRANCH;
}
// If this node is hidden mark it's children as hidden also
// If this node is hidden mark it's children as hidden also.
if ($this->hidden) {
$node->hidden = true;
}
// Return added node (reference returned by $this->children->add()
// Return added node (reference returned by $this->children->add().
return $node;
}
@@ -474,7 +489,7 @@ class navigation_node implements renderable {
* @param int $type One of navigation_node::TYPE_*
* @return navigation_node|false
*/
public function get($key, $type=null) {
public function get($key, $type = null) {
return $this->children->get($key, $type);
}
@@ -493,7 +508,7 @@ class navigation_node implements renderable {
* @return bool Returns true if it has children or could have (by AJAX expansion)
*/
public function has_children() {
return ($this->nodetype === navigation_node::NODETYPE_BRANCH || $this->children->count()>0 || $this->isexpandable);
return ($this->nodetype === self::NODETYPE_BRANCH || $this->children->count() > 0 || $this->isexpandable);
}
/**
@@ -569,8 +584,8 @@ class navigation_node implements renderable {
*/
public function remove_class($class) {
if (in_array($class, $this->classes)) {
$key = array_search($class,$this->classes);
if ($key!==false) {
$key = array_search($class, $this->classes);
if ($key !== false) {
// Remove the class' array element.
unset($this->classes[$key]);
// Reindex the array to avoid failures when the classes array is iterated later in mustache templates.
@@ -603,7 +618,7 @@ class navigation_node implements renderable {
/**
* Resets the page specific information on this node if it is being unserialised.
*/
public function __wakeup(){
public function __wakeup() {
$this->forceopen = false;
$this->isactive = false;
$this->remove_class('active_tree_node');
@@ -698,11 +713,11 @@ class navigation_node implements renderable {
* @param bool $shorttext If true shorttext is used rather than the normal text
* @return string
*/
public function get_content($shorttext=false) {
$navcontext = \context_helper::get_navigation_filter_context(null);
public function get_content($shorttext = false) {
$navcontext = context_helper::get_navigation_filter_context(null);
$options = !empty($navcontext) ? ['context' => $navcontext] : null;
if ($shorttext && $this->shorttext!==null) {
if ($shorttext && $this->shorttext !== null) {
return format_string($this->shorttext, null, $options);
} else {
return format_string($this->text, null, $options);
@@ -715,7 +730,7 @@ class navigation_node implements renderable {
* @return string
*/
public function get_title() {
if ($this->forcetitle || $this->action != null){
if ($this->forcetitle || $this->action != null) {
return $this->title;
} else {
return '';
@@ -744,7 +759,7 @@ class navigation_node implements renderable {
$url = $this->action()->url;
}
if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot.'/') === 0)) {
if (($url->out() === $CFG->wwwroot) || (strpos($url->out(), $CFG->wwwroot . '/') === 0)) {
return true;
}
}
@@ -767,7 +782,7 @@ class navigation_node implements renderable {
*/
public function get_css_type() {
if (array_key_exists($this->type, $this->namedtypes)) {
return 'type_'.$this->namedtypes[$this->type];
return 'type_' . $this->namedtypes[$this->type];
}
return 'type_unknown';
}
@@ -780,10 +795,10 @@ class navigation_node implements renderable {
public function find_expandable(array &$expandable) {
foreach ($this->children as &$child) {
if ($child->display && $child->has_children() && $child->children->count() == 0) {
$child->id = 'expandable_branch_'.$child->type.'_'.clean_param($child->key, PARAM_ALPHANUMEXT);
$child->id = 'expandable_branch_' . $child->type . '_' . clean_param($child->key, PARAM_ALPHANUMEXT);
$this->add_class('canexpand');
$child->requiresajaxloading = true;
$expandable[] = array('id' => $child->id, 'key' => $child->key, 'type' => $child->type);
$expandable[] = ['id' => $child->id, 'key' => $child->key, 'type' => $child->type];
}
$child->find_expandable($expandable);
}
@@ -823,11 +838,11 @@ class navigation_node implements renderable {
* @param bool $return
* @return array Array (tabs, selected, inactive, activated, return)
*/
public function get_tabs_array(array $inactive=array(), $return=false) {
$tabs = array();
$rows = array();
public function get_tabs_array(array $inactive = [], $return = false) {
$tabs = [];
$rows = [];
$selected = null;
$activated = array();
$activated = [];
foreach ($this->children as $node) {
$tabs[] = new tabobject($node->key, $node->action, $node->get_content(), $node->get_title());
if ($node->contains_active_node()) {
@@ -844,7 +859,7 @@ class navigation_node implements renderable {
}
}
}
return array(array($tabs, $rows), $selected, $inactive, $activated, $return);
return [[$tabs, $rows], $selected, $inactive, $activated, $return];
}
/**
@@ -854,11 +869,11 @@ class navigation_node implements renderable {
* @param navigation_node $parent
*/
public function set_parent(navigation_node $parent) {
// Set the parent (thats the easy part)
// Set the parent (thats the easy part).
$this->parent = $parent;
// Check if this node is active (this is checked during construction)
// Check if this node is active (this is checked during construction).
if ($this->isactive) {
// Force all of the parent nodes open so you can see this node
// Force all of the parent nodes open so you can see this node.
$this->parent->force_open();
// Make all parents inactive so that its clear where we are.
$this->parent->make_inactive();
@@ -892,7 +907,7 @@ class navigation_node implements renderable {
* @since Moodle 3.2
*/
public function action() {
if ($this->action instanceof moodle_url) {
if ($this->action instanceof url) {
return $this->action;
} else if ($this->action instanceof action_link) {
return $this->action->url;
@@ -907,10 +922,10 @@ class navigation_node implements renderable {
*/
public function actionattributes() {
if ($this->action instanceof action_link) {
return array_map(function($key, $value) {
return array_map(function ($key, $value) {
return [
'name' => $key,
'value' => $value
'value' => $value,
];
}, array_keys($this->action->attributes), $this->action->attributes);
}
@@ -940,7 +955,7 @@ class navigation_node implements renderable {
}
$actionid = $this->action->attributes['id'];
$actionsdata = array_map(function($action) use ($PAGE, $actionid) {
$actionsdata = array_map(function ($action) use ($PAGE, $actionid) {
$data = $action->export_for_template($PAGE->get_renderer('core'));
$data->id = $actionid;
return $data;
@@ -994,7 +1009,7 @@ class navigation_node implements renderable {
}
$node->add(
$lockstring,
new moodle_url(
new url(
'/admin/lock.php',
[
'id' => $context->id,
@@ -1003,11 +1018,10 @@ class navigation_node implements renderable {
self::TYPE_SETTING,
null,
'contextlocking',
new pix_icon($lockicon, '')
new pix_icon($lockicon, '')
);
}
}
}
/**
@@ -37,19 +37,19 @@ use Traversable;
* @copyright 2010 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class navigation_node_collection implements IteratorAggregate, Countable {
class navigation_node_collection implements Countable, IteratorAggregate {
/**
* A multidimensional array to where the first key is the type and the second
* key is the nodes key.
* @var array
*/
protected $collection = array();
protected $collection = [];
/**
* An array that contains references to nodes in the same order they were added.
* This is maintained as a progressive array.
* @var array
*/
protected $orderedcollection = array();
protected $orderedcollection = [];
/**
* A reference to the last node that was added to the collection
* @var navigation_node
@@ -68,28 +68,28 @@ class navigation_node_collection implements IteratorAggregate, Countable {
protected $collectionlabel = '';
/**
* Adds a navigation node to the collection
* Adds a navigation node to the collection.
*
* @param navigation_node $node Node to add
* @param string $beforekey If specified, adds before a node with this key,
* otherwise adds at end
* @return navigation_node Added node
*/
public function add(navigation_node $node, $beforekey=null) {
public function add(navigation_node $node, $beforekey = null) {
global $CFG;
$key = $node->key;
$type = $node->type;
// First check we have a 2nd dimension for this type
// First check we have a 2nd dimension for this type.
if (!array_key_exists($type, $this->orderedcollection)) {
$this->orderedcollection[$type] = array();
$this->orderedcollection[$type] = [];
}
// Check for a collision and report if debugging is turned on
// Check for a collision and report if debugging is turned on.
if ($CFG->debug && array_key_exists($key, $this->orderedcollection[$type])) {
debugging('Navigation node intersect: Adding a node that already exists '.$key, DEBUG_DEVELOPER);
debugging('Navigation node intersect: Adding a node that already exists ' . $key, DEBUG_DEVELOPER);
}
// Find the key to add before
// Find the key to add before.
$newindex = $this->count;
$last = true;
if ($beforekey !== null) {
@@ -107,11 +107,11 @@ class navigation_node_collection implements IteratorAggregate, Countable {
}
// Add the node to the appropriate place in the by-type structure (which
// is not ordered, despite the variable name)
// is not ordered, despite the variable name).
$this->orderedcollection[$type][$key] = $node;
if (!$last) {
// Update existing references in the ordered collection (which is the
// one that isn't called 'ordered') to shuffle them along if required
// one that isn't called 'ordered') to shuffle them along if required.
for ($oldindex = $this->count; $oldindex > $newindex; $oldindex--) {
$this->collection[$oldindex] = $this->collection[$oldindex - 1];
}
@@ -121,21 +121,22 @@ class navigation_node_collection implements IteratorAggregate, Countable {
// Update the last property to a reference to this new node.
$this->last = $this->orderedcollection[$type][$key];
// Reorder the array by index if needed
// Reorder the array by index if needed.
if (!$last) {
ksort($this->collection);
}
$this->count++;
// Return the reference to the now added node
// Return the reference to the now added node.
return $node;
}
/**
* Return a list of all the keys of all the nodes.
*
* @return array the keys.
*/
public function get_key_list() {
$keys = array();
$keys = [];
foreach ($this->collection as $node) {
$keys[] = $node->key;
}
@@ -167,14 +168,14 @@ class navigation_node_collection implements IteratorAggregate, Countable {
* @param int $type One of navigation_node::TYPE_*.
* @return navigation_node|null|false
*/
public function get($key, $type=null) {
public function get($key, $type = null) {
if ($type !== null) {
// If the type is known then we can simply check and fetch
// If the type is known then we can simply check and fetch.
if (!empty($this->orderedcollection[$type][$key])) {
return $this->orderedcollection[$type][$key];
}
} else {
// Because we don't know the type we look in the progressive array
// Because we don't know the type we look in the progressive array.
foreach ($this->collection as $node) {
if ($node->key === $key) {
return $node;
@@ -196,18 +197,24 @@ class navigation_node_collection implements IteratorAggregate, Countable {
* @param int $type One of navigation_node::TYPE_*.
* @return navigation_node|false
*/
public function find($key, $type=null) {
if ($type !== null && array_key_exists($type, $this->orderedcollection) && array_key_exists($key, $this->orderedcollection[$type])) {
public function find($key, $type = null) {
if (
$type !== null
&& array_key_exists($type, $this->orderedcollection)
&& array_key_exists($key, $this->orderedcollection[$type])
) {
return $this->orderedcollection[$type][$key];
} else {
$nodes = $this->getIterator();
// Search immediate children first
// Search immediate children first.
foreach ($nodes as &$node) {
if ($node->key === $key && ($type === null || $type === $node->type)) {
return $node;
}
}
// Now search each childs children
// Now search each childs children.
foreach ($nodes as &$node) {
$result = $node->children->find($key, $type);
if ($result !== false) {
@@ -235,7 +242,7 @@ class navigation_node_collection implements IteratorAggregate, Countable {
*/
public function type($type) {
if (!array_key_exists($type, $this->orderedcollection)) {
$this->orderedcollection[$type] = array();
$this->orderedcollection[$type] = [];
}
return $this->orderedcollection[$type];
}
@@ -246,7 +253,7 @@ class navigation_node_collection implements IteratorAggregate, Countable {
* @param int $type
* @return bool
*/
public function remove($key, $type=null) {
public function remove($key, $type = null) {
$child = $this->get($key, $type);
if ($child !== false) {
foreach ($this->collection as $colkey => $node) {
@@ -263,25 +270,12 @@ class navigation_node_collection implements IteratorAggregate, Countable {
return false;
}
/**
* Gets the number of nodes in this collection
*
* This option uses an internal count rather than counting the actual options to avoid
* a performance hit through the count function.
*
* @return int
*/
#[\Override]
public function count(): int {
return $this->count;
}
/**
* Gets an array iterator for the collection.
*
* This is required by the IteratorAggregator interface and is used by routines
* such as the foreach loop.
*
* @return ArrayIterator
*/
#[\Override]
public function getIterator(): Traversable {
return new ArrayIterator($this->collection);
}
File diff suppressed because it is too large Load Diff
@@ -19,13 +19,14 @@ namespace core\tests\navigation;
use core\exception\coding_exception;
use core\navigation\global_navigation;
// phpcs:disable
/**
* This is a dummy object that allows us to call protected methods within the
* global navigation class by prefixing the methods with `exposed_`
*/
class exposed_global_navigation extends global_navigation {
protected $exposedkey = 'exposed_';
public function __construct(?\moodle_page $page=null) {
public function __construct(?\moodle_page $page = null) {
global $PAGE;
if ($page === null) {
$page = $PAGE;
@@ -37,9 +38,12 @@ class exposed_global_navigation extends global_navigation {
$method = substr($method, strlen($this->exposedkey));
}
if (method_exists($this, $method)) {
return call_user_func_array(array($this, $method), $arguments);
return call_user_func_array([$this, $method], $arguments);
}
throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER);
throw new coding_exception(
'You have attempted to access a method that does not exist for the given object ' . $method,
DEBUG_DEVELOPER,
);
}
public function set_initialised() {
$this->initialised = true;
@@ -19,6 +19,8 @@ namespace core\tests\navigation;
use core\exception\coding_exception;
use core\navigation\settings_navigation;
// phpcs:disable
/**
* This is a dummy object that allows us to call protected methods within the
* global navigation class by prefixing the methods with `exposed_`.
@@ -27,7 +29,6 @@ use core\navigation\settings_navigation;
* @copyright Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class exposed_settings_navigation extends settings_navigation {
protected string $exposedkey = 'exposed_';
@@ -41,8 +42,11 @@ class exposed_settings_navigation extends settings_navigation {
$method = substr($method, strlen($this->exposedkey));
}
if (method_exists($this, $method)) {
return call_user_func_array(array($this, $method), $arguments);
return call_user_func_array([$this, $method], $arguments);
}
throw new coding_exception('You have attempted to access a method that does not exist for the given object '.$method, DEBUG_DEVELOPER);
throw new coding_exception(
'You have attempted to access a method that does not exist for the given object ' . $method,
DEBUG_DEVELOPER,
);
}
}
@@ -16,9 +16,9 @@
namespace core\tests\navigation;
use core\navigation\navigation_node;
use core\output\pix_icon;
use core\url;
use navigation_node;
/**
* TODO describe file navigation_testcase
@@ -28,7 +28,7 @@ use navigation_node;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class navigation_testcase extends \advanced_testcase {
protected function setup_node(): navigation_node {
protected function setup_node(): navigation_node { // phpcs:ignore
global $PAGE, $SITE;
// Perform a reset between tests to reset the PAGE.
@@ -49,16 +49,36 @@ abstract class navigation_testcase extends \advanced_testcase {
$demo1 = $node->add('demo1', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo1', new pix_icon('i/course', ''));
$demo2 = $node->add('demo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo2', new pix_icon('i/course', ''));
$demo3 = $node->add('demo3', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'demo3', new pix_icon('i/course', ''));
$demo4 = $demo3->add('demo4', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo4', new pix_icon('i/course', ''));
$demo4 = $demo3->add('demo4', $inactiveurl, navigation_node::TYPE_COURSE, null, 'demo4', new pix_icon('i/course', ''));
$demo5 = $demo3->add('demo5', $activeurl, navigation_node::TYPE_COURSE, null, 'demo5', new pix_icon('i/course', ''));
$demo5->add('activity1', null, navigation_node::TYPE_ACTIVITY, null, 'activity1')->make_active();
$demo6 = $demo3->add('demo6', null, navigation_node::TYPE_CONTAINER, 'container node test', 'demo6');
$hiddendemo1 = $node->add('hiddendemo1', $inactiveurl, navigation_node::TYPE_CATEGORY, null, 'hiddendemo1', new pix_icon('i/course', ''));
$hiddendemo1 = $node->add(
'hiddendemo1',
$inactiveurl,
navigation_node::TYPE_CATEGORY,
null,
'hiddendemo1',
new pix_icon('i/course', '')
);
$hiddendemo1->hidden = true;
$hiddendemo1->add('hiddendemo2', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo2', new pix_icon('i/course', ''))->helpbutton = 'Here is a help button';
$hiddendemo1->add('hiddendemo3', $inactiveurl, navigation_node::TYPE_COURSE, null, 'hiddendemo3', new pix_icon('i/course', ''))->display = false;
$hiddendemo1->add(
'hiddendemo2',
$inactiveurl,
navigation_node::TYPE_COURSE,
null,
'hiddendemo2',
new pix_icon('i/course', '')
)->helpbutton = 'Here is a help button';
$hiddendemo1->add(
'hiddendemo3',
$inactiveurl,
navigation_node::TYPE_COURSE,
null,
'hiddendemo3',
new pix_icon('i/course', '')
)->display = false;
return $node;
}
}
+4 -8
View File
@@ -26,7 +26,6 @@ namespace core\navigation;
*/
#[\PHPUnit\Framework\Attributes\CoversClass(navbar::class)]
final class navbar_test extends \advanced_testcase {
public function test_navbar_prepend_and_add(): \moodle_page {
global $PAGE;
// Unfortunate hack needed because people use global $PAGE around the place.
@@ -37,12 +36,12 @@ final class navbar_test extends \advanced_testcase {
$generator = self::getDataGenerator();
$cat1 = $generator->create_category();
$cat2 = $generator->create_category(array('parent' => $cat1->id));
$course = $generator->create_course(array('category' => $cat2->id));
$cat2 = $generator->create_category(['parent' => $cat1->id]);
$course = $generator->create_course(['category' => $cat2->id]);
$page = new \moodle_page();
$page->set_course($course);
$page->set_url(new \moodle_url('/course/view.php', array('id' => $course->id)));
$page->set_url(new \moodle_url('/course/view.php', ['id' => $course->id]));
$page->navbar->prepend('test 1');
$page->navbar->prepend('test 2');
$page->navbar->add('test 3');
@@ -67,10 +66,7 @@ final class navbar_test extends \advanced_testcase {
return $page;
}
/**
* @depends test_navbar_prepend_and_add
* @param $node
*/
#[\PHPUnit\Framework\Attributes\Depends('test_navbar_prepend_and_add')]
public function test_navbar_has_items(\moodle_page $page): void {
$this->resetAfterTest();
@@ -69,5 +69,4 @@ final class navigation_cache_test extends \advanced_testcase {
$this->assertTrue($cache->cached('software'));
$this->assertEquals($cache->software, 'Moodle');
}
}
@@ -34,12 +34,12 @@ final class navigation_node_test extends navigation_testcase {
public function test_node__construct(): void {
$node = $this->setup_node();
$fakeproperties = array(
$fakeproperties = [
'text' => 'text',
'shorttext' => 'A very silly extra long short text string, more than 25 characters',
'key' => 'key',
'type' => 'navigation_node::TYPE_COURSE',
'action' => new \moodle_url('http://www.moodle.org/'));
'action' => new \moodle_url('http://www.moodle.org/')];
$node = new navigation_node($fakeproperties);
$this->assertSame($fakeproperties['text'], $node->text);
@@ -53,7 +53,14 @@ final class navigation_node_test extends navigation_testcase {
$node = $this->setup_node();
// Add a node with all args set.
$node1 = $node->add('test_add_1', 'http://www.moodle.org/', navigation_node::TYPE_COURSE, 'testadd1', 'key', new pix_icon('i/course', ''));
$node1 = $node->add(
'test_add_1',
'http://www.moodle.org/',
navigation_node::TYPE_COURSE,
'testadd1',
'key',
new pix_icon('i/course', ''),
);
// Add a node with the minimum args required.
$node2 = $node->add('test_add_2', null, navigation_node::TYPE_CUSTOM, 'testadd2');
$node3 = $node->add(str_repeat('moodle ', 15), str_repeat('moodle', 15));
@@ -79,12 +86,27 @@ final class navigation_node_test extends navigation_testcase {
$node = $this->setup_node();
// Create 3 nodes.
$node1 = navigation_node::create('test_add_1', null, navigation_node::TYPE_CUSTOM,
'test 1', 'testadd1');
$node2 = navigation_node::create('test_add_2', null, navigation_node::TYPE_CUSTOM,
'test 2', 'testadd2');
$node3 = navigation_node::create('test_add_3', null, navigation_node::TYPE_CUSTOM,
'test 3', 'testadd3');
$node1 = navigation_node::create(
'test_add_1',
null,
navigation_node::TYPE_CUSTOM,
'test 1',
'testadd1'
);
$node2 = navigation_node::create(
'test_add_2',
null,
navigation_node::TYPE_CUSTOM,
'test 2',
'testadd2'
);
$node3 = navigation_node::create(
'test_add_3',
null,
navigation_node::TYPE_CUSTOM,
'test 3',
'testadd3'
);
// Add node 2, then node 1 before 2, then node 3 at end.
$node->add_node($node2);
$node->add_node($node1, 'testadd2');
@@ -93,9 +115,9 @@ final class navigation_node_test extends navigation_testcase {
foreach ($node->children as $child) {
$keys[] = $child->key;
}
$this->assertSame('testadd1', $keys[count($keys)-3]);
$this->assertSame('testadd2', $keys[count($keys)-2]);
$this->assertSame('testadd3', $keys[count($keys)-1]);
$this->assertSame('testadd1', $keys[count($keys) - 3]);
$this->assertSame('testadd2', $keys[count($keys) - 2]);
$this->assertSame('testadd3', $keys[count($keys) - 1]);
}
public function test_node_add_class(): void {
@@ -191,7 +213,7 @@ final class navigation_node_test extends navigation_testcase {
public function test_node_find_expandable(): void {
$node = $this->setup_node();
$expandable = array();
$expandable = [];
$node->find_expandable($expandable);
$this->assertCount(0, $expandable);
@@ -361,15 +383,18 @@ final class navigation_node_test extends navigation_testcase {
return [
'The navigation node has an action link.' =>
[
navigation_node::create('Node', new action_link(new \moodle_url('/'), '',
new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING),
true
navigation_node::create('Node', new action_link(
new \moodle_url('/'),
'',
new popup_action('click', new \moodle_url('/'))
), navigation_node::TYPE_SETTING),
true,
],
'The navigation node does not have an action link.' =>
[
navigation_node::create('Node', new \moodle_url('/'), navigation_node::TYPE_SETTING),
false
false,
],
];
}
@@ -393,7 +418,7 @@ final class navigation_node_test extends navigation_testcase {
'id' => $node->action->attributes['id'],
'event' => $node->action->actions[0]->event,
'jsfunction' => $node->action->actions[0]->jsfunction,
'jsfunctionargs' => json_encode($node->action->actions[0]->jsfunctionargs)
'jsfunctionargs' => json_encode($node->action->actions[0]->jsfunctionargs),
];
$this->assertEquals($expected, $data['actions'][0]);
} else { // There are no actions added to the action link.
@@ -414,13 +439,19 @@ final class navigation_node_test extends navigation_testcase {
return [
'The navigation node has an action link with an action attached.' =>
[
navigation_node::create('Node', new action_link(new \moodle_url('/'), '',
new popup_action('click', new \moodle_url('/'))), navigation_node::TYPE_SETTING),
navigation_node::create('Node', new action_link(
new \moodle_url('/'),
'',
new popup_action('click', new \moodle_url('/'))
), navigation_node::TYPE_SETTING),
],
'The navigation node has an action link without an action.' =>
[
navigation_node::create('Node', new action_link(new \moodle_url('/'), '', null),
navigation_node::TYPE_SETTING),
navigation_node::create(
'Node',
new action_link(new \moodle_url('/'), '', null),
navigation_node::TYPE_SETTING
),
],
'The navigation node does not have an action link.' =>
[
@@ -19,13 +19,14 @@ namespace core\navigation;
use core\tests\navigation\exposed_settings_navigation;
/**
* Tests for
* Tests for
*
* @package core
* @category test
* @copyright 2025 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
#[\PHPUnit\Framework\Attributes\CoversClass(settings_navigation::class)]
final class settings_navigation_test extends \advanced_testcase {
public function test_setting___construct(): settings_navigation {
global $PAGE, $SITE;
@@ -80,7 +81,7 @@ final class settings_navigation_test extends \advanced_testcase {
$PAGE->set_course($SITE);
// Check that a standard user can not view the preferences page.
$studentrole = $DB->get_record('role', array('shortname' => 'student'));
$studentrole = $DB->get_record('role', ['shortname' => 'student']);
$this->getDataGenerator()->role_assign($studentrole->id, $persondoingtheviewing->id);
$this->setUser($persondoingtheviewing);
$settingsnav = new exposed_settings_navigation();
@@ -89,7 +90,7 @@ final class settings_navigation_test extends \advanced_testcase {
$this->assertFalse($settingsnav->can_view_user_preferences($persontoview->id));
// Set persondoingtheviewing as a manager.
$managerrole = $DB->get_record('role', array('shortname' => 'manager'));
$managerrole = $DB->get_record('role', ['shortname' => 'manager']);
$this->getDataGenerator()->role_assign($managerrole->id, $persondoingtheviewing->id);
$settingsnav = new exposed_settings_navigation();
$settingsnav->initialise();
@@ -104,5 +105,4 @@ final class settings_navigation_test extends \advanced_testcase {
$preferencenode = $settingsnav->find('userviewingsettings' . $persontoview->id, null);
$this->assertTrue($settingsnav->can_view_user_preferences($persontoview->id));
}
}