76 lines
2.1 KiB
PHP
76 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Domovoy\Repositories;
|
|
|
|
use PDO;
|
|
use Domovoy\Models\User;
|
|
|
|
class UserRepository
|
|
{
|
|
private PDO $pdo;
|
|
|
|
public function __construct(PDO $pdo)
|
|
{
|
|
$this->pdo = $pdo;
|
|
}
|
|
|
|
public function findById(string $id): ?User
|
|
{
|
|
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = :id');
|
|
$stmt->execute(['id' => $id]);
|
|
$row = $stmt->fetch();
|
|
return $row ? User::fromArray($row) : null;
|
|
}
|
|
|
|
public function findByUsername(string $username): ?User
|
|
{
|
|
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE username = :username');
|
|
$stmt->execute(['username' => $username]);
|
|
$row = $stmt->fetch();
|
|
return $row ? User::fromArray($row) : null;
|
|
}
|
|
|
|
public function findAll(): array
|
|
{
|
|
$stmt = $this->pdo->query('SELECT * FROM users ORDER BY created_at DESC');
|
|
$users = [];
|
|
while ($row = $stmt->fetch()) {
|
|
$users[] = User::fromArray($row);
|
|
}
|
|
return $users;
|
|
}
|
|
|
|
public function count(): int
|
|
{
|
|
$stmt = $this->pdo->query('SELECT COUNT(*) FROM users');
|
|
return (int) $stmt->fetchColumn();
|
|
}
|
|
|
|
public function save(User $user): void
|
|
{
|
|
if ($user->id === null) {
|
|
$user->id = \Ramsey\Uuid\Uuid::uuid4()->toString();
|
|
}
|
|
|
|
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
|
|
$user->updatedAt = new \DateTimeImmutable($now);
|
|
if ($user->createdAt === null) {
|
|
$user->createdAt = new \DateTimeImmutable($now);
|
|
}
|
|
|
|
$stmt = $this->pdo->prepare(
|
|
'INSERT INTO users (id, username, password_hash, created_at, updated_at)
|
|
VALUES (:id, :username, :password_hash, :created_at, :updated_at)'
|
|
);
|
|
$stmt->execute([
|
|
'id' => $user->id,
|
|
'username' => $user->username,
|
|
'password_hash' => $user->passwordHash,
|
|
'created_at' => $user->createdAt->format('Y-m-d H:i:s'),
|
|
'updated_at' => $user->updatedAt->format('Y-m-d H:i:s'),
|
|
]);
|
|
}
|
|
}
|