Files
2026-06-04 19:19:35 +03:00

88 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Repositories;
final class AdminRepository extends BaseRepository
{
public function activeCount(): int
{
return (int) $this->pdo()
->query('SELECT COUNT(*) FROM admins WHERE is_active = 1')
->fetchColumn();
}
/**
* @return array<string, mixed>|null
*/
public function findActiveByEmail(string $email): ?array
{
$statement = $this->pdo()->prepare(
'SELECT id, name, email, password_hash, role
FROM admins
WHERE email = :email AND is_active = 1
LIMIT 1'
);
$statement->execute(['email' => mb_strtolower(trim($email))]);
$admin = $statement->fetch();
return $admin === false ? null : $admin;
}
/**
* @return array<string, mixed>|null
*/
public function findActiveById(int $id): ?array
{
$statement = $this->pdo()->prepare(
'SELECT id, name, email, role
FROM admins
WHERE id = :id AND is_active = 1
LIMIT 1'
);
$statement->execute(['id' => $id]);
$admin = $statement->fetch();
return $admin === false ? null : $admin;
}
public function createOwner(string $name, string $email, string $password): int
{
$name = trim($name);
$email = mb_strtolower(trim($email));
if ($name === '' || $email === '' || $password === '') {
throw new \InvalidArgumentException('Имя, email и пароль обязательны.');
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('Укажите корректный email.');
}
if (mb_strlen($password) < 8) {
throw new \InvalidArgumentException('Пароль должен быть не короче 8 символов.');
}
$statement = $this->pdo()->prepare(
'INSERT INTO admins (name, email, password_hash, role, is_active)
VALUES (:name, :email, :password_hash, "owner", 1)'
);
$statement->execute([
'name' => $name,
'email' => $email,
'password_hash' => password_hash($password, PASSWORD_DEFAULT),
]);
return (int) $this->pdo()->lastInsertId();
}
public function touchLastLogin(int $id): void
{
$statement = $this->pdo()->prepare(
'UPDATE admins SET last_login_at = NOW() WHERE id = :id'
);
$statement->execute(['id' => $id]);
}
}