Files
hyperf-micro-svc/app/Service/Admin/AdminUser/RoleService.php
2025-09-17 16:17:55 +08:00

139 lines
3.4 KiB
PHP

<?php
/**
* This service file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Service\Admin\AdminUser;
use App\Common\Repository\AdminMenuRepository;
use App\Common\Repository\AdminRoleRepository;
use App\Exception\ErrException;
use App\Model\AdminMenu;
use App\Service\Admin\BaseAdminService;
use Hyperf\Collection\Arr;
use Hyperf\Di\Annotation\Inject;
class RoleService extends BaseAdminService
{
/**
* @var AdminRoleRepository
*/
#[Inject]
protected AdminRoleRepository $adminRoleRepository;
/**
* @var AdminMenuRepository
*/
#[Inject]
protected AdminMenuRepository $adminMenuRepository;
/**
* @return array
*/
public function handle(): array
{
return $this->adminReturn->success(
'success',
$this->adminRoleRepository->page(
$this->getRequestData(),
$this->getCurrentPage(),
$this->getPageSize()
)
);
}
/**
* @return array
*/
public function create(): array
{
if (!$this->adminRoleRepository->create(
array_merge(
$this->getRequestData(),
['created_by' => $this->adminId]
)
)) throw new ErrException('添加失败');
return $this->adminReturn->success();
}
/**
* @param int $id
* @return array
*/
public function update(int $id): array
{
if (!$this->adminRoleRepository->updateById(
$id,
array_merge(
$this->getRequestData(),
['updated_by' => $this->adminId]
)
)) throw new ErrException('更新失败');
return $this->adminReturn->success();
}
/**
* @return array
*/
public function delete(): array
{
if (!$this->adminRoleRepository->deleteById($this->getRequestData())) throw new ErrException('删除失败');
return $this->adminReturn->success();
}
/**
* @param int $id
* @return array
*/
public function getRole(int $id): array
{
return $this->adminReturn->success(
'success',
$this->adminRoleRepository
->findById($id)
->adminMenus()
->get()
->map(static fn (AdminMenu $adminMenu) => $adminMenu->only([
'id' , 'name'
]))->toArray()
);
}
/**
* @param int $id
* @return array
*/
public function setRole(int $id): array
{
if (!$this->adminRoleRepository->existsById($id)) throw new ErrException('角色不存在');
$permissionsCode = Arr::get($this->getRequestData(), 'permissions', []);
if (count($permissionsCode) === 0) {
$this->adminRoleRepository->findById($id)->adminMenus()->detach();
return $this->adminReturn->success();
}
if (!$this->adminRoleRepository
->findById($id)
->adminMenus()
->sync(
$this->adminMenuRepository
->list([
'code' => $permissionsCode
])
->map(static fn ($item) => $item->id)
->toArray()
)) throw new ErrException('更新失败');
return $this->adminReturn->success();
}
}