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 18 /** @var string[] list of Item classes to load */ 19 protected $types = []; 20 21 /** @var int the context this menu is used in */ 22 protected $context = AbstractItem::CTX_DESKTOP; 23 24 /** @var string view identifier to be set in the event */ 25 protected $view = ''; 26 27 /** 28 * AbstractMenu constructor. 29 * 30 * @param int $context the context this menu is used in 31 */ 32 public function __construct($context = AbstractItem::CTX_DESKTOP) 33 { 34 $this->context = $context; 35 } 36 37 /** 38 * Get the list of action items in this menu 39 * 40 * @return AbstractItem[] 41 * @triggers MENU_ITEMS_ASSEMBLY 42 */ 43 public function getItems() 44 { 45 $data = ['view' => $this->view, 'items' => []]; 46 Event::createAndTrigger('MENU_ITEMS_ASSEMBLY', $data, [$this, 'loadItems']); 47 return $data['items']; 48 } 49 50 /** 51 * Default action for the MENU_ITEMS_ASSEMBLY event 52 * 53 * @param array $data The plugin data 54 * @see getItems() 55 */ 56 public function loadItems(&$data) 57 { 58 foreach ($this->types as $class) { 59 try { 60 $class = "\\dokuwiki\\Menu\\Item\\$class"; 61 /** @var AbstractItem $item */ 62 $item = new $class(); 63 if (!$item->visibleInContext($this->context)) continue; 64 $data['items'][] = $item; 65 } catch (\RuntimeException $ignored) { 66 // item not available 67 } 68 } 69 } 70 71 /** 72 * Generate HTML list items for this menu 73 * 74 * This is a convenience method for template authors. If you need more fine control over the 75 * output, use getItems() and build the HTML yourself 76 * 77 * @param string|false $classprefix create a class from type with this prefix, false for no class 78 * @param bool $svg add the SVG link 79 * @return string 80 */ 81 public function getListItems($classprefix = '', $svg = true) 82 { 83 $html = ''; 84 foreach ($this->getItems() as $item) { 85 if ($classprefix !== false) { 86 $class = ' class="' . $classprefix . $item->getType() . '"'; 87 } else { 88 $class = ''; 89 } 90 91 $html .= "<li$class>"; 92 $html .= $item->asHtmlLink(false, $svg); 93 $html .= '</li>'; 94 } 95 return $html; 96 } 97} 98