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 return $data['items']; 47 } 48 49 /** 50 * Default action for the MENU_ITEMS_ASSEMBLY event 51 * 52 * @param array $data The plugin data 53 * @see getItems() 54 */ 55 public function loadItems(&$data) 56 { 57 foreach ($this->types as $class) { 58 try { 59 $class = "\\dokuwiki\\Menu\\Item\\$class"; 60 /** @var AbstractItem $item */ 61 $item = new $class(); 62 if (!$item->visibleInContext($this->context)) continue; 63 $data['items'][] = $item; 64 } catch (\RuntimeException $ignored) { 65 // item not available 66 } 67 } 68 } 69 70 /** 71 * Generate HTML list items for this menu 72 * 73 * This is a convenience method for template authors. If you need more fine control over the 74 * output, use getItems() and build the HTML yourself 75 * 76 * @param string|false $classprefix create a class from type with this prefix, false for no class 77 * @param bool $svg add the SVG link 78 * @return string 79 */ 80 public function getListItems($classprefix = '', $svg = true) 81 { 82 $html = ''; 83 foreach ($this->getItems() as $item) { 84 if ($classprefix !== false) { 85 $class = ' class="' . $classprefix . $item->getType() . '"'; 86 } else { 87 $class = ''; 88 } 89 90 $html .= "<li$class>"; 91 $html .= $item->asHtmlLink(false, $svg); 92 $html .= '</li>'; 93 } 94 return $html; 95 } 96} 97