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.

332 lines
11 KiB

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. foreach ($items as $i => $item) {
  165. /* 获取菜单项的自定义属性 */
  166. $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
  167. $tag = ArrayHelper::remove($options, 'tag', 'li');
  168. $class = [];
  169. if ($item['active']) {
  170. $class[] = $this->activeCssClass;
  171. if (isset($item['items'])) {
  172. $class[] = $this->menuOpenClass;
  173. }
  174. }
  175. if ($i === 0 && $this->firstItemCssClass !== null) {
  176. $class[] = $this->firstItemCssClass;
  177. }
  178. if ($i === $n - 1 && $this->lastItemCssClass !== null) {
  179. $class[] = $this->lastItemCssClass;
  180. }
  181. if (isset($item['items'])) {
  182. $class[] = 'treeview';
  183. }
  184. if (isset($item['is_header']) && $item['is_header']) {
  185. $class[] = "header";
  186. }
  187. Html::addCssClass($options, $class);
  188. $menu = $this->renderItem($item);
  189. if (!empty($item['items'])) {
  190. $submenuTemplate = ArrayHelper::getValue($item, 'submenuTemplate', $this->submenuTemplate);
  191. $menu .= strtr($submenuTemplate, [
  192. '{items}' => $this->renderItems($item['items']),
  193. ]);
  194. }
  195. $lines[] = Html::tag($tag, $menu, $options);
  196. }
  197. return implode("\n", $lines);
  198. }
  199. /**
  200. * 渲染菜单项
  201. * @param array $item
  202. * @return string 渲染结果
  203. */
  204. protected function renderItem($item) {
  205. if (isset($item['url'])) {
  206. if (isset($item['template'])) {
  207. $template = $item['template'];
  208. } else {
  209. $template = isset($item['items']) ? $this->linkTemplateWithSub : $this->linkTemplateNoSub;
  210. }
  211. return strtr($template, [
  212. '{url}' => Html::encode(Url::to($item['url'])),
  213. '{label}' => Html::encode($item['label']),
  214. '{icon}' => Html::encode($item['icon'])
  215. ]);
  216. }
  217. $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
  218. return strtr($template, [
  219. '{label}' => $item['label'],
  220. ]);
  221. }
  222. /**
  223. * 判断菜单项是否被选中
  224. * @param $item array
  225. * @return boolean $item
  226. */
  227. protected function isItemActive($item) {
  228. if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
  229. $route = Yii::getAlias($item['url'][0]);
  230. if ($route[0] !== '/' && Yii::$app->controller) {
  231. $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
  232. }
  233. if (ltrim($route, '/') !== $this->route) {
  234. return false;
  235. }
  236. return true;
  237. }
  238. return false;
  239. }
  240. /**
  241. * 格式化菜单item
  242. * @param string $item
  243. * @param bool $active
  244. */
  245. protected function normalizeItems($items, &$active) {
  246. foreach ($items as $i => $item) {
  247. /* 去除visible 为 false的item */
  248. if (isset($item['visible']) && !$item['visible']) {
  249. unset($items[$i]);
  250. continue;
  251. }
  252. /* 添加默认icon */
  253. if (!isset($item['icon'])) {
  254. if (!empty($this->defaultIcon)) {
  255. $items[$i]['icon'] = $this->defaultIcon;
  256. }
  257. }
  258. /* 添加label */
  259. if (!isset($item['label'])) {
  260. $item['label'] = '';
  261. }
  262. /* 转义HTML */
  263. $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
  264. if ($encodeLabel) {
  265. $items[$i]['label'] = Html::encode($item['label']);
  266. }
  267. /* 格式化子菜单 item */
  268. $hasActiveChild = false;
  269. if (isset($item['items'])) {
  270. $items[$i]['items'] = $this->normalizeItems($item['items'], $hasActiveChild);
  271. if (empty($items[$i]['items']) && $this->hideEmptyItems) {
  272. unset($items[$i]['items']);
  273. }
  274. }
  275. /* 处理菜单是否被选中 */
  276. if (!isset($item['active'])) {
  277. if ($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item)) {
  278. $active = $items[$i]['active'] = true;
  279. }
  280. } elseif ($item['active'] instanceof Closure) {
  281. $active = $items[$i]['active'] = call_user_func($item['active'], $item, $hasActiveChild, $this->isItemActive($item), $this);
  282. } elseif ($item['active']) {
  283. $active = true;
  284. }
  285. }
  286. return array_values($items);
  287. }
  288. }