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'); } /** * 初始化菜单的通用属性。 *
* 例如说,只有目录或者菜单类型的菜单,才设置 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); } }