MenuService.php 2.9 KB

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