MDL-71823 user: Add hook for extending user menu

This commit is contained in:
Guillaume Barat 2024-07-16 21:12:13 +10:00 committed by guillaumebarat
parent f6141a67d8
commit eadf38cf45
3 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,7 @@
issueNumber: MDL-71823
notes:
core_user:
- message: >-
New '\core_user\hook\extend_user_menu' hook added to allow third party
plugin to extend the user menu navigation
type: improved

View File

@ -0,0 +1,62 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_user\hook;
/**
* Hook to modify user menu.
*
* @package core_user
* @copyright 2024 Guillaume Barat <guillaumebarat@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @property-read \renderer_base $renderer The page renderer object
*/
#[\core\attribute\tags('user')]
#[\core\attribute\label('Allows plugins to add any elements to the user menu')]
final class extend_user_menu {
/**
* Hook to modify user menu.
*
* @param array $navitems Menu item to add.
*/
public function __construct(
/** @var array The navigation items */
public array $navitems = [],
) {
}
/**
* Add navigation item.
*
* @param null|\stdClass $output
*/
public function add_navitem(?\stdClass $output): void {
if ($output) {
if (property_exists($output, 'itemtype')) {
$this->navitems[] = $output;
}
}
}
/**
* Returns a class with the detail for the menu.
*
* @return array
*/
public function get_navitems(): array {
return $this->navitems;
}
}

View File

@ -22,6 +22,10 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use core\di;
use core\hook;
use core_user\hook\extend_user_menu;
define('USER_FILTER_ENROLMENT', 1);
define('USER_FILTER_GROUP', 2);
define('USER_FILTER_LAST_ACCESS', 3);
@ -909,6 +913,14 @@ function user_get_user_navigation_info($user, $page, $options = array()) {
}
}
// Call to hook to add menu items.
$hook = new extend_user_menu();
di::get(core\hook\manager::class)->dispatch($hook);
$hookitems = $hook->get_navitems();
foreach ($hookitems as $menuitem) {
$returnobject->navitems[] = $menuitem;
}
if ($custommenucount > 0) {
// Only add a divider if we have customusermenuitems.
$divider = new stdClass();