Menu.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace app\admin\controller;
  3. use app\admin\middleware\Login;
  4. use app\Request;
  5. class Menu extends Base
  6. {
  7. /**
  8. * 中间件校验
  9. * @var array[]
  10. */
  11. protected $middleware = [
  12. Login::class => ['except' => ['']],
  13. ];
  14. /**
  15. * 获取菜单
  16. * @param Request $request
  17. */
  18. public function list(Request $request)
  19. {
  20. $menuJson = file_get_contents(root_path() . "config/json/menu.json");
  21. $menu = json_decode($menuJson, true);
  22. $role_codes = [];
  23. $role_codes[] = 'home';
  24. $role_codes[] = 'admin';
  25. $fin_menu = $this->getFinMenu($menu, $role_codes,1);
  26. $result = [
  27. 'menu' => $fin_menu,
  28. 'role' => $role_codes,
  29. ];
  30. return $this->success($result);
  31. }
  32. /**
  33. * @param $menu_list
  34. * @param $role_codes
  35. * @param int $is_root
  36. * @return array
  37. */
  38. public function getFinMenu($menu_list, $role_codes, int $is_root = 0): array
  39. {
  40. $fin_menu = [];
  41. foreach ($menu_list as $key => $val) {
  42. if (isset($val['children'])) {
  43. $child_list = $this->getChild($val['children']);
  44. $parents = false;
  45. foreach ($child_list as $kes => $ves) {
  46. if (in_array($ves['role'], $role_codes) || $is_root) {
  47. $parents = true;
  48. break;
  49. }
  50. }
  51. if (in_array($val['role'], $role_codes) || $parents) {
  52. $item = $val;
  53. $item['children'] = $this->getFinMenu($val['children'], $role_codes, $is_root);
  54. $fin_menu[] = $item;
  55. }
  56. } else {
  57. if (isset($val['role'])) {
  58. if (in_array($val['role'], $role_codes) || $is_root || $val['role'] == 'index') {
  59. $fin_menu[] = $val;
  60. }
  61. }
  62. }
  63. }
  64. return $fin_menu;
  65. }
  66. /**
  67. * 获取所有子节点
  68. * @param array $arrData
  69. * @param string $strChild
  70. * @return array|mixed
  71. */
  72. public function getChild(array $arrData = [], string $strChild = "children"): mixed
  73. {
  74. if (empty($arrData) || !is_array($arrData)) {
  75. return $arrData;
  76. }
  77. $arrRes = [];
  78. foreach ($arrData as $k => $v) {
  79. $arrTmp = $v;
  80. if (isset($arrTmp[$strChild])) {
  81. unset($arrTmp[$strChild]);
  82. }
  83. $arrRes[] = $arrTmp;
  84. if (isset($v[$strChild])) {
  85. if (!empty($v[$strChild])) {
  86. $arrTmp = $this->getChild($v[$strChild]);
  87. $arrRes = array_merge($arrRes, $arrTmp);
  88. }
  89. }
  90. }
  91. return $arrRes;
  92. }
  93. }