105 lines
2.9 KiB
PHP
105 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\User;
|
|
|
|
use App\Shared\ValueObject\EmailAddress;
|
|
use DateTimeImmutable;
|
|
use DateTimeZone;
|
|
use RuntimeException;
|
|
|
|
class EloquentUserRepository implements UserRepository
|
|
{
|
|
public function create(CreateUserDto $dto): User
|
|
{
|
|
$model = UserModel::create([
|
|
'email' => $dto->email->value(),
|
|
'display_name' => $dto->displayName,
|
|
'password_hash' => $dto->passwordHash,
|
|
'is_admin' => $dto->isAdmin,
|
|
'email_confirmed_at' => $dto->emailConfirmedAt,
|
|
]);
|
|
|
|
return $this->toDomain($model);
|
|
}
|
|
|
|
public function find(int $id): ?User
|
|
{
|
|
$model = UserModel::find($id);
|
|
|
|
return $model === null ? null : $this->toDomain($model);
|
|
}
|
|
|
|
public function findByEmail(EmailAddress $email): ?User
|
|
{
|
|
$model = UserModel::where('email', $email->value())->first();
|
|
|
|
return $model === null ? null : $this->toDomain($model);
|
|
}
|
|
|
|
public function findByDisplayName(string $displayName): ?User
|
|
{
|
|
$model = UserModel::where('display_name', $displayName)->first();
|
|
|
|
return $model === null ? null : $this->toDomain($model);
|
|
}
|
|
|
|
/**
|
|
* @return User[]
|
|
*/
|
|
public function search(string $query): array
|
|
{
|
|
$like = strtolower($query).'%';
|
|
$models = UserModel::query()
|
|
->whereRaw('LOWER(display_name) LIKE ?', [$like])
|
|
->orWhereRaw('LOWER(email) LIKE ?', [$like])
|
|
->orderBy('display_name')
|
|
->get();
|
|
|
|
return $models->map(
|
|
function (UserModel $model) {
|
|
return $this->toDomain($model);
|
|
},
|
|
)->all();
|
|
}
|
|
|
|
/**
|
|
* @throws RuntimeException
|
|
*/
|
|
public function update(User $user): User
|
|
{
|
|
$model = UserModel::find($user->getId());
|
|
if ($model === null) {
|
|
throw new RuntimeException(
|
|
"User with id: {$user->getId()} does not exist"
|
|
);
|
|
}
|
|
$model->email = $user->getEmail()->value();
|
|
$model->display_name = $user->getDisplayName();
|
|
$model->password_hash = $user->getPasswordHash();
|
|
$model->is_admin = $user->isAdmin();
|
|
$model->email_confirmed_at = $user->getEmailConfirmedAt();
|
|
$model->save();
|
|
|
|
return $this->toDomain($model);
|
|
}
|
|
|
|
private function toDomain(UserModel $model): User
|
|
{
|
|
$confirmedAt = null;
|
|
if ($model->email_confirmed_at !== null) {
|
|
$confirmedAt = new DateTimeImmutable(
|
|
$model->email_confirmed_at->toDateTimeString(),
|
|
new DateTimeZone('UTC'),
|
|
);
|
|
}
|
|
|
|
return new User(
|
|
id: $model->id,
|
|
email: new EmailAddress($model->email),
|
|
displayName: $model->display_name,
|
|
passwordHash: $model->password_hash,
|
|
isAdmin: $model->is_admin,
|
|
emailConfirmedAt: $confirmedAt,
|
|
);
|
|
}
|
|
}
|