1<?php 2 3namespace dokuwiki\Menu; 4 5use dokuwiki\Extension\Event; 6use dokuwiki\Menu\Item\AbstractItem; 7 8/** 9 * Class AbstractMenu 10 * 11 * Basic menu functionality. A menu defines a list of AbstractItem that shall be shown. 12 * It contains convenience functions to display the menu in HTML, but template authors can also 13 * just accesst the items via getItems() and create the HTML as however they see fit. 14 */ 15abstract class AbstractMenu implements MenuInterface 16{ 17 /** @var string[] list of Item classes to load */ 18 protected $types = []; 19 20 /** @var int the context this menu is used in */ 21 protected $context = AbstractItem::CTX_DESKTOP; 22 23 /** @var string view identifier to be set in the event */ 24 protected $view = ''; 25 26 /** 27 * AbstractMenu constructor. 28 * 29 * @param int $context the context this menu is used in 30 */ 31 public function __construct($context = AbstractItem::CTX_DESKTOP) 32 { 33 $this->context = $context; 34 } 35 36 /** 37 * Get the list of action items in this menu 38 * 39 * @return AbstractItem[] 40 * @triggers MENU_ITEMS_ASSEMBLY 41 */ 42 public function getItems() 43 { 44 $data = ['view' => $this->view, 'items' => []]; 45 Event::createAndTrigger('MENU_ITEMS_ASSEMBLY', $data, [$this, 'loadItems']); 46 47 $data['items'] = array_filter( 48 $data['items'], 49 fn($item) => $item instanceof AbstractItem && $item->visibleInContext($this->context) 50 ); 51 52 return $data['items']; 53 } 54 55 /** 56 * Default action for the MENU_ITEMS_ASSEMBLY event 57 * 58 * @param array $data The plugin data 59 * @see getItems() 60 */ 61 public function loadItems(&$data) 62 { 63 foreach ($this->types as $class) { 64 try { 65 $class = "\\dokuwiki\\Menu\\Item\\$class"; 66 /** @var AbstractItem $item */ 67 $item = new $class(); 68 $data['items'][] = $item; 69 } catch (\RuntimeException $ignored) { 70 // item not available 71 } 72 } 73 } 74 75 /** 76 * Generate HTML list items for this menu 77 * 78 * This is a convenience method for template authors. If you need more fine control over the 79 * output, use getItems() and build the HTML yourself 80 * 81 * @param string|false $classprefix create a class from type with this prefix, false for no class 82 * @param bool $svg add the SVG link 83 * @return string 84 */ 85 public function getListItems($classprefix = '', $svg = true) 86 { 87 $html = ''; 88 foreach ($this->getItems() as $item) { 89 if ($classprefix !== false) { 90 $class = ' class="' . $classprefix . $item->getType() . '"'; 91 } else { 92 $class = ''; 93 } 94 95 $html .= "<li$class>"; 96 $html .= $item->asHtmlLink(false, $svg); 97 $html .= '</li>'; 98 } 99 return $html; 100 } 101} 102