MenuService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * @Name
  4. * @Description
  5. * @Author 刘学玺
  6. * @Date 2024/8/15 14:30
  7. */
  8. namespace App\Http\Services\Backend\Server\System;
  9. use App\Enums\System\MenuType;
  10. use App\Exceptions\ApiException;
  11. use App\Http\Services\Service;
  12. use App\Models\System\Menu;
  13. class MenuService extends Service
  14. {
  15. /**
  16. * @throws ApiException
  17. */
  18. public function createMenu($params)
  19. {
  20. // 校验父菜单存在
  21. self::validateParentMenu($params['parent_id'], null);
  22. // 校验菜单(自己)
  23. self::validateMenu($params['parent_id'], $params['name'], null);
  24. // 插入数据库
  25. $menu = self::toModel($params, Menu::class);
  26. self::initMenuProperty($menu);
  27. $menu->save();
  28. return $menu->id;
  29. }
  30. /**
  31. * @throws ApiException
  32. */
  33. protected static function validateParentMenu($parentId, $childId): void
  34. {
  35. if (!$parentId) return;
  36. // 不能设置自己为父菜单
  37. $parentId === $childId && self::error('MENU_PARENT_ERROR');
  38. $menu = Menu::query()->find($parentId);
  39. // 父菜单不存在
  40. !$menu && self::error('MENU_PARENT_NOT_EXISTS');
  41. // 父菜单必须是目录或者菜单类型
  42. $menu->type != MenuType::DIR && $menu->type != MenuType::MENU && self::error('MENU_PARENT_NOT_DIR_OR_MENU');
  43. }
  44. /**
  45. * @throws ApiException
  46. */
  47. protected static function validateMenu($parentId, $name, $id): void
  48. {
  49. $where = ['parent_id' => $parentId, 'name' => $name];
  50. $menu = Menu::query()->where($where)->first();
  51. if (is_null($menu)) return;
  52. // 如果 id 为空,说明不用比较是否为相同 id 的菜单
  53. !$id && self::error('MENU_NAME_DUPLICATE');
  54. $menu->id !== $id && self::error('MENU_NAME_DUPLICATE');
  55. }
  56. /**
  57. * 初始化菜单的通用属性。
  58. * <p>
  59. * 例如说,只有目录或者菜单类型的菜单,才设置 icon
  60. *
  61. */
  62. private static function initMenuProperty(&$menu): void
  63. {
  64. // 菜单为按钮类型时,无需 component、icon、path 属性,进行置空
  65. if ($menu->type === MenuType::BUTTON) {
  66. $menu->component = null;
  67. $menu->componentName = null;
  68. $menu->icon = null;
  69. $menu->path = null;
  70. }
  71. isset($menu->permission) && ($menu->permission = $menu->permission ?: null);
  72. }
  73. }