Menu.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace app\common\library;
  3. use app\admin\model\AuthRule;
  4. use fast\Tree;
  5. use think\exception\PDOException;
  6. class Menu
  7. {
  8. /**
  9. * 创建菜单
  10. * @param array $menu
  11. * @param mixed $parent 父类的name或pid
  12. */
  13. public static function create($menu, $parent = 0)
  14. {
  15. if (!is_numeric($parent))
  16. {
  17. $parentRule = AuthRule::getByName($parent);
  18. $pid = $parentRule ? $parentRule['id'] : 0;
  19. }
  20. else
  21. {
  22. $pid = $parent;
  23. }
  24. $allow = array_flip(['file', 'name', 'title', 'icon', 'condition', 'remark', 'ismenu']);
  25. foreach ($menu as $k => $v)
  26. {
  27. $hasChild = isset($v['sublist']) && $v['sublist'] ? true : false;
  28. $data = array_intersect_key($v, $allow);
  29. $data['ismenu'] = isset($data['ismenu']) ? $data['ismenu'] : ($hasChild ? 1 : 0);
  30. $data['icon'] = isset($data['icon']) ? $data['icon'] : ($hasChild ? 'fa fa-list' : 'fa fa-circle-o');
  31. $data['pid'] = $pid;
  32. $data['status'] = 'normal';
  33. try
  34. {
  35. $menu = AuthRule::create($data);
  36. if ($hasChild)
  37. {
  38. self::create($v['sublist'], $menu->id);
  39. }
  40. }
  41. catch (PDOException $e)
  42. {
  43. print_r($e);
  44. }
  45. }
  46. }
  47. /**
  48. * 删除菜单
  49. * @param string $name 规则name
  50. * @return boolean
  51. */
  52. public static function delete($name)
  53. {
  54. $menu = AuthRule::getByName($name);
  55. if ($menu)
  56. {
  57. // 必须将结果集转换为数组
  58. $ruleList = collection(model('AuthRule')->order('weigh', 'desc')->field('id,pid,name')->select())->toArray();
  59. // 构造菜单数据
  60. $ids = Tree::instance()->init($ruleList)->getChildrenIds($menu['id'], true);
  61. if ($ids)
  62. {
  63. AuthRule::destroy($ids);
  64. }
  65. return true;
  66. }
  67. return false;
  68. }
  69. }