Menu.php 2.1 KB

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