building-sign/app/traits/cms/MenuTrait.php

99 lines
2.6 KiB
PHP
Executable File

<?php
namespace app\traits\cms;
use app\model\Menu;
use app\repository\CmsRepository;
use think\Collection;
trait MenuTrait
{
// 获取菜单列表
public function getMenuList(string $type = 'all', string $show = 'all'): Collection
{
return Menu::field("id,pid,title,type,name,icon,href,target,sort")
->where('status', Menu::STATUS_NORMAL)
->when($type != 'all', function ($q) use ($show) {
$q->where('is_show', $show);
})
->when($type != 'all', function ($q) use ($type) {
$q->where('type', $type);
})
->order('sort', 'desc')
->order('id', 'asc')
->select();
}
//递归获取子菜单
public function buildMenuChild(int $pid, array $menus, string $childName = 'children', bool $excludeParent = false): array
{
$treeList = [];
foreach ($menus as $v) {
if ($pid == $v['pid']) {
$node = $v;
$node['has_children'] = false;
$child = $this->buildMenuChild($v['id'], $menus, $childName, $excludeParent);
if (!empty($child)) {
$node[$childName] = $child;
$node['has_children'] = true;
if ($excludeParent) {
$node['disabled'] = true;
}
}
$treeList[] = $node;
}
}
return $treeList;
}
//菜单权限过滤
public function handMenuRule(int $accountId, array $menus): array
{
$rules = CmsRepository::getInstance()->getUserRules($accountId);
foreach ($menus as $k => $m) {
$menus[$k]['icon'] = !empty($m['icon']) ? 'fa '.$m['icon'] : '';
$menus[$k]['href'] = ltrim($m['href'], '/');
if ($m['pid'] !== 0) {
$name = $m['name'];
$nameArr = explode(':', $name);
if (count($nameArr) <= 1) {
$name = $name.':index';
}
if (!in_array($name, $rules)) {
unset($menus[$k]);
}
}
}
return $menus;
}
/**
* 检测批量数据下 是否有子栏目
*
* @param array $ids
* @return bool
*/
public function hasChildrenMenuByIds(array $ids): bool
{
return Menu::whereIn('pid', $ids)->count() > 0;
}
/**
* 批量删除
*
* @param array $ids
* @return bool
*/
public function delMenuByIds(array $ids): bool
{
return Menu::deleteByIds($ids);
}
}