You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

333 lines
11 KiB

5 years ago
5 years ago
5 years ago
  1. <?php
  2. /*
  3. * The MIT License
  4. *
  5. * Copyright 2019 Blobt.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. */
  25. namespace blobt\widgets;
  26. use Yii;
  27. use yii\base\Widget;
  28. use yii\helpers\ArrayHelper;
  29. use yii\helpers\Html;
  30. use yii\helpers\Url;
  31. /**
  32. * 参照yii\widgets\Menu,根据AdminLTE样式从写的一个小物件
  33. * @author Blobt
  34. * @email 380255922@qq.com
  35. * 使用例子
  36. * <?php
  37. * echo Menu::widget([
  38. * 'items' => [
  39. * ['label' => 'MAIN NAVIGATION', 'is_header' => true],
  40. * ['label' => 'Documentation', 'url' => 'https:www.baidu.com', 'icon' => 'fa-book'],
  41. * ['label' => 'Products', 'url' => ['product/index'], 'items' => [
  42. * ['label' => 'New Arrivals', 'url' => ['product/index', 'tag' => 'new']],
  43. * ['label' => 'Most Popular', 'url' => ['product/index', 'tag' => 'popular']],
  44. * ]],
  45. * ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
  46. * ]
  47. * ]);
  48. * ?>
  49. *
  50. *
  51. */
  52. class Menu extends Widget {
  53. /**
  54. * @var array 菜单的item数组。
  55. * 菜单的item同时也是一个数组,结构如下所述:
  56. * lable: string, optional,指定选项的label
  57. * encode:boolean, optional,label是否需要转义
  58. * url: string or array, optional, 生产菜单的路径
  59. * 产生结果和yii的Url::to()方法一致,并且会套用[[linkTemplate]]模板
  60. * visible: boolean, optional, 选项是否可见,默认是true(可见)
  61. * active: boolean or Closure, optional, 是否被选中
  62. * 如果为true,则会在css中添加[[activeCssClass]]
  63. * 当使用Closure时候,匿名函数必须是`function ($item, $hasActiveChild, $isItemActive, $widget)`
  64. * 匿名函数必须返回true或者false
  65. * 如果不是使用匿名函数,就会使用[[isItemActive]]来判断item是否被选中
  66. * items: array, optional, 指定子菜单选项,格式和父菜单是一样的
  67. * template: string, optional,选项的渲染模板
  68. * submenuTemplate: string, optional, 子菜单渲染模板
  69. * options: array, optional, 指定html属性
  70. */
  71. public $items = [];
  72. /**
  73. * @var array html属性,这些指定的属性会加到所有的item中
  74. */
  75. public $itemOptions = [];
  76. /**
  77. * @var string 链接的渲染模板
  78. */
  79. public $linkTemplateWithSub = "<a href=\"{url}\"><i class=\"fa {icon}\"></i><span>{label}</span><span class=\"pull-right-container\"><i class=\"fa fa-angle-left pull-right\"></i></span></a>";
  80. public $linkTemplateNoSub = "<a href=\"{url}\"><i class=\"fa {icon}\"></i><span>{label}</span></a>";
  81. /**
  82. * @var string label的渲染模板
  83. */
  84. public $labelTemplate = '{label}';
  85. /**
  86. * @var string 子菜单的渲染模板
  87. */
  88. public $submenuTemplate = "\n<ul class=\"treeview-menu\">\n{items}\n</ul>\n";
  89. /**
  90. * @var boolean label是否要进行html转义
  91. */
  92. public $encodeLabels = true;
  93. /**
  94. * @var string 被选中的菜单的CSS类
  95. */
  96. public $activeCssClass = 'active';
  97. /**
  98. * @var string 控制二级菜单开合
  99. */
  100. public $menuOpenClass = 'menu-open';
  101. /**
  102. * @var boolean 是否根据路由去判断菜单项是否被选中
  103. */
  104. public $activateItems = true;
  105. /**
  106. * @var boolean 当某一个子菜单的选中时候是否也关联选中父菜单
  107. */
  108. public $activateParents = true;
  109. /**
  110. * @var boolean 如果item的url没有设置时,是否不显示该item
  111. */
  112. public $hideEmptyItems = true;
  113. /**
  114. * @var array 菜单容器标签的属性
  115. */
  116. public $options = [
  117. 'class' => 'sidebar-menu',
  118. 'data-widget' => 'tree'
  119. ];
  120. /**
  121. * @var string 第一个菜单item的css类
  122. */
  123. public $firstItemCssClass;
  124. /**
  125. * @var string 最后一个菜单item的css类
  126. */
  127. public $lastItemCssClass;
  128. /**
  129. * @var string 路由 ,run的时候会自动获取当前路由
  130. */
  131. public $route;
  132. /**
  133. * @var string $_GET参数
  134. */
  135. public $params;
  136. /**
  137. * @var string 菜单项默认Icon
  138. */
  139. public $defaultIcon = 'fa-circle-o';
  140. /**
  141. * 渲染菜单
  142. */
  143. public function run() {
  144. if ($this->route === null && Yii::$app->controller !== null) {
  145. $this->route = Yii::$app->controller->getRoute();
  146. }
  147. if ($this->params === null) {
  148. $this->params = Yii::$app->request->getQueryParams();
  149. }
  150. $items = $this->normalizeItems($this->items, $hasActiveChild);
  151. if (!empty($items)) {
  152. $options = $this->options;
  153. $tag = ArrayHelper::remove($options, 'tag', 'ul');
  154. return Html::tag($tag, $this->renderItems($items), $options);
  155. }
  156. }
  157. /**
  158. * 渲染菜单
  159. * @param array $items
  160. * @return string 渲染结果
  161. */
  162. protected function renderItems($items) {
  163. $lines = [];
  164. $n = count($items);
  165. foreach ($items as $i => $item) {
  166. /* 获取菜单项的自定义属性 */
  167. $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
  168. $tag = ArrayHelper::remove($options, 'tag', 'li');
  169. $class = [];
  170. if (isset($item['active'])) {
  171. $class[] = $this->activeCssClass;
  172. if (isset($item['items'])) {
  173. $class[] = $this->menuOpenClass;
  174. }
  175. }
  176. if ($i === 0 && $this->firstItemCssClass !== null) {
  177. $class[] = $this->firstItemCssClass;
  178. }
  179. if ($i === $n - 1 && $this->lastItemCssClass !== null) {
  180. $class[] = $this->lastItemCssClass;
  181. }
  182. if (isset($item['items'])) {
  183. $class[] = 'treeview';
  184. }
  185. if (isset($item['is_header']) && $item['is_header']) {
  186. $class[] = "header";
  187. }
  188. Html::addCssClass($options, $class);
  189. $menu = $this->renderItem($item);
  190. if (!empty($item['items'])) {
  191. $submenuTemplate = ArrayHelper::getValue($item, 'submenuTemplate', $this->submenuTemplate);
  192. $menu .= strtr($submenuTemplate, [
  193. '{items}' => $this->renderItems($item['items']),
  194. ]);
  195. }
  196. $lines[] = Html::tag($tag, $menu, $options);
  197. }
  198. return implode("\n", $lines);
  199. }
  200. /**
  201. * 渲染菜单项
  202. * @param array $item
  203. * @return string 渲染结果
  204. */
  205. protected function renderItem($item) {
  206. if (isset($item['url'])) {
  207. if (isset($item['template'])) {
  208. $template = $item['template'];
  209. } else {
  210. $template = isset($item['items']) ? $this->linkTemplateWithSub : $this->linkTemplateNoSub;
  211. }
  212. return strtr($template, [
  213. '{url}' => Html::encode(Url::to($item['url'])),
  214. '{label}' => Html::encode($item['label']),
  215. '{icon}' => Html::encode($item['icon'])
  216. ]);
  217. }
  218. $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
  219. return strtr($template, [
  220. '{label}' => $item['label'],
  221. ]);
  222. }
  223. /**
  224. * 判断菜单项是否被选中
  225. * @param $item array
  226. * @return boolean $item
  227. */
  228. protected function isItemActive($item) {
  229. if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
  230. $route = Yii::getAlias($item['url'][0]);
  231. if ($route[0] !== '/' && Yii::$app->controller) {
  232. $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
  233. }
  234. if (ltrim($route, '/') !== $this->route) {
  235. return false;
  236. }
  237. return true;
  238. }
  239. return false;
  240. }
  241. /**
  242. * 格式化菜单item
  243. * @param string $item
  244. * @param bool $active
  245. */
  246. protected function normalizeItems($items, &$active) {
  247. foreach ($items as $i => $item) {
  248. /* 去除visible 为 false的item */
  249. if (isset($item['visible']) && !$item['visible']) {
  250. unset($items[$i]);
  251. continue;
  252. }
  253. /* 添加默认icon */
  254. if (!isset($item['icon'])) {
  255. if (!empty($this->defaultIcon)) {
  256. $items[$i]['icon'] = $this->defaultIcon;
  257. }
  258. }
  259. /* 添加label */
  260. if (!isset($item['label'])) {
  261. $item['label'] = '';
  262. }
  263. /* 转义HTML */
  264. $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
  265. if ($encodeLabel) {
  266. $items[$i]['label'] = Html::encode($item['label']);
  267. }
  268. /* 格式化子菜单 item */
  269. $hasActiveChild = false;
  270. if (isset($item['items'])) {
  271. $items[$i]['items'] = $this->normalizeItems($item['items'], $hasActiveChild);
  272. if (empty($items[$i]['items']) && $this->hideEmptyItems) {
  273. unset($items[$i]['items']);
  274. }
  275. }
  276. /* 处理菜单是否被选中 */
  277. if (!isset($item['active'])) {
  278. if ($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item)) {
  279. $active = $items[$i]['active'] = true;
  280. }
  281. } elseif ($item['active'] instanceof Closure) {
  282. $active = $items[$i]['active'] = call_user_func($item['active'], $item, $hasActiveChild, $this->isItemActive($item), $this);
  283. } elseif ($item['active']) {
  284. $active = true;
  285. }
  286. }
  287. return array_values($items);
  288. }
  289. }