Files
FamilyBook/app/Account.php
T

93 lines
3.0 KiB
PHP
Raw Normal View History

<?php
/**
* 登录账号。一个人最多一个账号,账号依附于「人」而存在。
*/
declare(strict_types=1);
namespace App;
final class Account
{
public const ROLES = ['admin', 'member', 'guest'];
public static function findByPerson(int $personId): ?array
{
$st = Database::get()->prepare('SELECT * FROM accounts WHERE person_id = ?');
$st->execute([$personId]);
$row = $st->fetch();
return $row ?: null;
}
public static function create(int $personId, string $password, string $role = 'member'): int
{
$role = in_array($role, self::ROLES, true) ? $role : 'member';
$st = Database::get()->prepare(
'INSERT INTO accounts (person_id, password_hash, role) VALUES (?, ?, ?)'
);
$st->execute([$personId, password_hash($password, PASSWORD_DEFAULT), $role]);
return (int)Database::get()->lastInsertId();
}
public static function setPassword(int $accountId, string $password): void
{
Database::get()->prepare('UPDATE accounts SET password_hash = ? WHERE id = ?')
->execute([password_hash($password, PASSWORD_DEFAULT), $accountId]);
}
public static function setRole(int $accountId, string $role): void
{
$role = in_array($role, self::ROLES, true) ? $role : 'member';
Database::get()->prepare('UPDATE accounts SET role = ? WHERE id = ?')
->execute([$role, $accountId]);
}
public static function setStatus(int $accountId, string $status): void
{
Database::get()->prepare('UPDATE accounts SET status = ? WHERE id = ?')
->execute([$status, $accountId]);
}
/** 各角色各有多少人(设置页显示) */
public static function roleCounts(): array
{
$st = Database::get()->query(
"SELECT role, COUNT(*) AS n FROM accounts WHERE status = 'active' GROUP BY role"
);
$out = ['admin' => 0, 'member' => 0, 'guest' => 0];
foreach ($st->fetchAll() as $r) {
$out[(string)$r['role']] = (int)$r['n'];
}
return $out;
}
public static function roleWord(string $role): string
{
return ['admin' => '管理员', 'member' => '家庭成员', 'guest' => '访客'][$role] ?? '成员';
}
/** 管理员不能被停用/降权 —— 否则全家人都会被锁在系统外面 */
public static function adminCount(): int
{
$st = Database::get()->prepare(
"SELECT COUNT(*) FROM accounts a
JOIN persons p ON p.id = a.person_id
WHERE a.role = 'admin' AND a.status = 'active'"
);
$st->execute();
return (int)$st->fetchColumn();
}
public static function validatePassword(string $password): array
{
$err = [];
if (strlen($password) < 8) {
$err[] = '密码至少 8 位';
}
if (!preg_match('/[0-9]/', $password) || !preg_match('/[A-Za-z]/', $password)) {
$err[] = '密码要同时包含字母和数字';
}
return $err;
}
}