1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议 https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
namespace app\common\service;
use app\common\constants\MenuConstant;
use think\facade\Db;
class MenuService
{
/**
* 管理员ID
* @var integer
*/
protected $adminId;
public function __construct($adminId)
{
$this->adminId = $adminId;
return $this;
}
/**
* 获取首页信息
* @return array|\think\Model|null
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function getHomeInfo()
{
$data = Db::name('system_menu')
->field('title,icon,href')
->where("delete_time is null")
->where('pid', MenuConstant::HOME_PID)
->find();
!empty($data) && $data['href'] = __url($data['href']);
return $data;
}
/**
* 获取后台菜单树信息
* @return mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function getMenuTree()
{
/** @var AuthService $authService */
$authServer = app(AuthService::class, ['adminId' => $this->adminId]);
return $this->buildMenuChild(0, $this->getMenuData(),$authServer);
}
private function buildMenuChild($pid, $menuList, AuthService $authServer)
{
$treeList = [];
foreach ($menuList as &$v) {
$check = empty($v['href']) ? true : $authServer->checkNode($v['href']);
!empty($v['href']) && $v['href'] = __url($v['href']);
if ($pid == $v['pid'] && $check) {
$node = $v;
$child = $this->buildMenuChild($v['id'], $menuList, $authServer);
if (!empty($child)) {
$node['child'] = $child;
}
if (!empty($v['href']) || !empty($child)) {
$treeList[] = $node;
}
}
}
return $treeList;
}
/**
* 获取所有菜单数据
* @return \think\Collection
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
protected function getMenuData()
{
$menuData = Db::name('system_menu')
->field('id,pid,title,icon,href,target')
->where("delete_time is null")
->where([
['status', '=', '1'],
['pid', '<>', MenuConstant::HOME_PID],
])
->order([
'sort' => 'desc',
'id' => 'asc',
])
->select();
return $menuData;
}
}