70 lines
1.8 KiB
PHP
70 lines
1.8 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
class User extends DB\SQL\Mapper
|
||
{
|
||
public function __construct()
|
||
{
|
||
parent::__construct(Base::instance()->get('DB'), 'users');
|
||
}
|
||
|
||
public static function bootstrap(DB\SQL $db): void
|
||
{
|
||
if ($db->schema('users', null, 0)) {
|
||
return;
|
||
}
|
||
|
||
$db->exec('CREATE TABLE users (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
username TEXT NOT NULL UNIQUE,
|
||
password_hash TEXT NOT NULL,
|
||
created_at TEXT NOT NULL
|
||
)');
|
||
}
|
||
|
||
public function findPublic(int $id): ?array
|
||
{
|
||
if ($id <= 0) {
|
||
return null;
|
||
}
|
||
|
||
$this->load(['id = ?', $id]);
|
||
if ($this->dry()) {
|
||
return null;
|
||
}
|
||
|
||
return [
|
||
'id' => (int) $this->id,
|
||
'username' => (string) $this->username,
|
||
'created_at' => (string) $this->created_at,
|
||
];
|
||
}
|
||
|
||
public function create(string $username, string $password): int
|
||
{
|
||
$username = Base::instance()->clean(trim($username));
|
||
$password = trim($password);
|
||
|
||
if ($username === '' || $password === '') {
|
||
throw new RuntimeException('Nom d’utilisateur et mot de passe obligatoires.');
|
||
}
|
||
if (mb_strlen($password) < 10) {
|
||
throw new RuntimeException('Le mot de passe doit contenir au moins 10 caractères.');
|
||
}
|
||
|
||
$this->load(['username = ?', $username]);
|
||
if (!$this->dry()) {
|
||
throw new RuntimeException('Cet utilisateur existe déjà.');
|
||
}
|
||
|
||
$this->reset();
|
||
$this->username = $username;
|
||
$this->password_hash = password_hash($password, PASSWORD_DEFAULT);
|
||
$this->created_at = app_now();
|
||
$this->save();
|
||
|
||
return (int) $this->id;
|
||
}
|
||
}
|