53 lines
1.4 KiB
PHP
53 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\User\UseCases\PromoteUserToAdmin;
|
|
|
|
use App\Exceptions\BadRequestException;
|
|
use App\Exceptions\ForbiddenException;
|
|
use App\User\User;
|
|
use App\User\UserRepository;
|
|
use DomainException;
|
|
|
|
class PromoteUserToAdmin
|
|
{
|
|
public function __construct(
|
|
private UserRepository $userRepo,
|
|
) {}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
* @throws ForbiddenException
|
|
* @throws DomainException
|
|
*/
|
|
public function execute(PromoteUserToAdminRequest $request): User
|
|
{
|
|
if (! $request->requesterIsAdmin) {
|
|
throw new ForbiddenException(
|
|
'only admins can promote users'
|
|
);
|
|
}
|
|
if ($request->targetUserId <= 0) {
|
|
throw new BadRequestException(
|
|
'targetUserId must be positive'
|
|
);
|
|
}
|
|
|
|
$target = $this->userRepo->find($request->targetUserId);
|
|
if ($target === null) {
|
|
throw new DomainException('user not found');
|
|
}
|
|
|
|
if ($target->isAdmin()) {
|
|
return $target;
|
|
}
|
|
|
|
return $this->userRepo->update(new User(
|
|
id: $target->getId(),
|
|
email: $target->getEmail(),
|
|
displayName: $target->getDisplayName(),
|
|
passwordHash: $target->getPasswordHash(),
|
|
isAdmin: true,
|
|
emailConfirmedAt: $target->getEmailConfirmedAt(),
|
|
));
|
|
}
|
|
}
|