131 lines
3.1 KiB
PHP
131 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace Lucent\Account;
|
|
|
|
use Carbon\Carbon;
|
|
use Lucent\Database\Database;
|
|
use Lucent\Primitive\Collection;
|
|
use Lucent\Option\Option;
|
|
|
|
class UserRepoLunar implements UserRepo
|
|
{
|
|
private $tableName = "lunar_staff";
|
|
|
|
public function count(): int
|
|
{
|
|
return Database::make()->table($this->tableName)->count();
|
|
}
|
|
|
|
/**
|
|
* @return Collection<User>
|
|
*/
|
|
public function all(): Collection
|
|
{
|
|
$usersData = Database::make()->table($this->tableName)->get();
|
|
|
|
$users = array_map(
|
|
fn($userData) => $this->fromArray((array) $userData),
|
|
$usersData->toArray(),
|
|
);
|
|
return new Collection($users);
|
|
}
|
|
|
|
public function insert(User $user): void
|
|
{
|
|
$userData = toArray($user);
|
|
$userData["roles"] = json_encode($userData["roles"]);
|
|
Database::make()->table($this->tableName)->insert($userData);
|
|
}
|
|
|
|
public function update(User $user): void
|
|
{
|
|
$userData = toArray($user);
|
|
$userData["roles"] = json_encode($userData["roles"]);
|
|
Database::make()
|
|
->table($this->tableName)
|
|
->where("id", $user->id)
|
|
->update($userData);
|
|
}
|
|
|
|
public function updateLoginToken(string $id): string
|
|
{
|
|
$newToken = Token::new(32);
|
|
|
|
Database::make()
|
|
->table($this->tableName)
|
|
->where("id", $id)
|
|
->update([
|
|
"loggedInAt" => Carbon::now()->toJson(),
|
|
"mailToken" => $newToken,
|
|
]);
|
|
|
|
return $newToken;
|
|
}
|
|
|
|
/**
|
|
* @return Option<User>
|
|
*/
|
|
public function findByEmail(Email $email): Option
|
|
{
|
|
$user = Database::make()
|
|
->table($this->tableName)
|
|
->where("email", $email->value())
|
|
->first();
|
|
|
|
if (empty($user)) {
|
|
return none();
|
|
}
|
|
|
|
return some($this->fromArray((array) $user));
|
|
}
|
|
|
|
/**
|
|
* @return Option<User>
|
|
*/
|
|
public function findById(string $id): Option
|
|
{
|
|
$user = Database::make()
|
|
->table($this->tableName)
|
|
->where("id", $id)
|
|
->first();
|
|
|
|
if (empty($user)) {
|
|
return none();
|
|
}
|
|
|
|
return some($this->fromArray((array) $user));
|
|
}
|
|
|
|
public function updateName(string $userId, Name $name): void
|
|
{
|
|
Database::make()
|
|
->table($this->tableName)
|
|
->where("id", $userId)
|
|
->update(["name" => $name->value]);
|
|
}
|
|
|
|
public function updateEmail(string $userId, Email $email): void
|
|
{
|
|
Database::make()
|
|
->table($this->tableName)
|
|
->where("id", $userId)
|
|
->update(["email" => $email->value()]);
|
|
}
|
|
|
|
public function fromArray(array $data): User
|
|
{
|
|
return new User(
|
|
id: $data["id"],
|
|
name: new Name(
|
|
$data["first_name"] . " " . $data["last_name"] ?? "",
|
|
),
|
|
email: new Email($data["email"]),
|
|
roles: [],
|
|
createdAt: $data["created_at"],
|
|
updatedAt: $data["updated_at"],
|
|
loggedInAt: null,
|
|
mailToken: null,
|
|
);
|
|
}
|
|
}
|