123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- /**
- * @Name
- * @Description
- * @Author 刘学玺
- * @Date 2024/8/15 14:30
- */
- namespace App\Http\Services\Backend\Server\System;
- use App\Enums\System\MenuType;
- use App\Exceptions\ApiException;
- use App\Http\Services\Service;
- use App\Models\System\Menu;
- class MenuService extends Service
- {
- /**
- * @throws ApiException
- */
- public function createMenu($params)
- {
- // 校验父菜单存在
- self::validateParentMenu($params['parent_id'], null);
- // 校验菜单(自己)
- self::validateMenu($params['parent_id'], $params['name'], null);
- // 插入数据库
- $menu = self::toModel($params, Menu::class);
- self::initMenuProperty($menu);
- $menu->save();
- return $menu->id;
- }
- /**
- * @throws ApiException
- */
- protected static function validateParentMenu($parentId, $childId): void
- {
- if (!$parentId) return;
- // 不能设置自己为父菜单
- $parentId === $childId && self::error('MENU_PARENT_ERROR');
- $menu = Menu::query()->find($parentId);
- // 父菜单不存在
- !$menu && self::error('MENU_PARENT_NOT_EXISTS');
- // 父菜单必须是目录或者菜单类型
- $menu->type != MenuType::DIR && $menu->type != MenuType::MENU && self::error('MENU_PARENT_NOT_DIR_OR_MENU');
- }
- /**
- * @throws ApiException
- */
- protected static function validateMenu($parentId, $name, $id): void
- {
- $where = ['parent_id' => $parentId, 'name' => $name];
- $menu = Menu::query()->where($where)->first();
- if (is_null($menu)) return;
- // 如果 id 为空,说明不用比较是否为相同 id 的菜单
- !$id && self::error('MENU_NAME_DUPLICATE');
- $menu->id !== $id && self::error('MENU_NAME_DUPLICATE');
- }
- /**
- * 初始化菜单的通用属性。
- * <p>
- * 例如说,只有目录或者菜单类型的菜单,才设置 icon
- *
- */
- private static function initMenuProperty(&$menu): void
- {
- // 菜单为按钮类型时,无需 component、icon、path 属性,进行置空
- if ($menu->type === MenuType::BUTTON) {
- $menu->component = null;
- $menu->componentName = null;
- $menu->icon = null;
- $menu->path = null;
- }
- isset($menu->permission) && ($menu->permission = $menu->permission ?: null);
- }
- }
|