Attainly/backend/app/User/EloquentUserRepository.php

66 lines
1.5 KiB
PHP

<?php
namespace App\User;
use App\Shared\ValueObject\EmailAddress;
use DomainException;
class EloquentUserRepository implements UserRepository
{
public function create(CreateUserDto $dto): User
{
$model = UserModel::create([
'email' => $dto->email->value(),
'passwordHash' => $dto->passwordHash,
]);
return $this->toDomain($model);
}
public function find(int $id): ?User
{
$model = UserModel::find($id);
if ($model === null) {
return null;
}
return $this->toDomain($model);
}
public function findByEmail(EmailAddress $email): ?User
{
$model = UserModel::query()
->where('email', $email->value())
->first();
if ($model === null) {
return null;
}
return $this->toDomain($model);
}
public function update(User $user): User
{
$model = UserModel::find($user->getId());
if ($model === null) {
throw new DomainException(
"User with id {$user->getId()} not found",
);
}
$model->email = $user->getEmail()->value();
$model->passwordHash = $user->getPasswordHash();
$model->save();
return $this->toDomain($model);
}
private function toDomain(UserModel $model): User
{
return new User(
id: $model->id,
email: new EmailAddress($model->email),
passwordHash: $model->passwordHash,
);
}
}