77 lines
2.4 KiB
PHP
77 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\User\UseCases\SignupUser;
|
|
|
|
use App\Auth\PasswordHasher;
|
|
use App\Exceptions\BadRequestException;
|
|
use App\Shared\ValueObject\EmailAddress;
|
|
use App\User\CreateUserDto;
|
|
use App\User\User;
|
|
use App\User\UserRepository;
|
|
use DomainException;
|
|
use InvalidArgumentException;
|
|
|
|
class SignupUser
|
|
{
|
|
private const MIN_PASSWORD_LENGTH = 8;
|
|
|
|
private const DISPLAY_NAME_PATTERN = '/^[a-z0-9_-]{3,30}$/';
|
|
|
|
public function __construct(
|
|
private UserRepository $userRepo,
|
|
private PasswordHasher $hasher,
|
|
) {}
|
|
|
|
/**
|
|
* @throws BadRequestException
|
|
* @throws DomainException
|
|
*/
|
|
public function execute(SignupUserRequest $request): User
|
|
{
|
|
if ($request->email === null || $request->email === '') {
|
|
throw new BadRequestException('email is required');
|
|
}
|
|
if ($request->displayName === null || $request->displayName === '') {
|
|
throw new BadRequestException('displayName is required');
|
|
}
|
|
if (
|
|
preg_match(
|
|
self::DISPLAY_NAME_PATTERN,
|
|
$request->displayName,
|
|
) !== 1
|
|
) {
|
|
throw new BadRequestException(
|
|
'displayName must be 3-30 chars of [a-z0-9_-]'
|
|
);
|
|
}
|
|
if ($request->password === null || $request->password === '') {
|
|
throw new BadRequestException('password is required');
|
|
}
|
|
if (strlen($request->password) < self::MIN_PASSWORD_LENGTH) {
|
|
throw new BadRequestException(
|
|
'password must be at least '.self::MIN_PASSWORD_LENGTH.' characters'
|
|
);
|
|
}
|
|
|
|
try {
|
|
$email = new EmailAddress($request->email);
|
|
} catch (InvalidArgumentException $exception) {
|
|
throw new BadRequestException($exception->getMessage());
|
|
}
|
|
|
|
if ($this->userRepo->findByEmail($email) !== null) {
|
|
throw new DomainException('email already registered');
|
|
}
|
|
if ($this->userRepo->findByDisplayName($request->displayName) !== null) {
|
|
throw new DomainException('displayName already taken');
|
|
}
|
|
|
|
return $this->userRepo->create(new CreateUserDto(
|
|
email: $email,
|
|
displayName: $request->displayName,
|
|
passwordHash: $this->hasher->hash($request->password),
|
|
isAdmin: false,
|
|
emailConfirmedAt: null,
|
|
));
|
|
}
|
|
}
|