motorradig2027/motorradig/src/Models/User.php

75 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models;
use App\Core\Model;
class User extends Model
{
protected static string $table = 'users';
public static function byEmail(string $email): ?static
{
$row = db()->fetchOne('SELECT * FROM `users` WHERE email = ?', [$email]);
return $row === null ? null : static::fromRow($row);
}
/** Sucht einen Benutzer anhand des Namens (optional ohne eine bestimmte ID). */
public static function byName(string $name, ?int $excludeId = null): ?static
{
$name = self::normalizeName($name);
$sql = 'SELECT * FROM `users` WHERE name = ?';
$params = [$name];
if ($excludeId !== null) {
$sql .= ' AND id <> ?';
$params[] = $excludeId;
}
$sql .= ' LIMIT 1';
$row = db()->fetchOne($sql, $params);
return $row === null ? null : static::fromRow($row);
}
/** Vereinheitlicht Leerzeichen im Namen. */
public static function normalizeName(string $name): string
{
return trim(preg_replace('/\s+/u', ' ', $name) ?? '');
}
/** Admins und Tour Guides, die als Tour Guide wählbar sind. */
public static function selectableGuides(): array
{
$rows = db()->fetchAll(
'SELECT * FROM `users` WHERE role IN (?, ?) ORDER BY name',
['ADMIN', 'TOUR GUIDE']
);
return array_map(fn(array $row) => static::fromRow($row), $rows);
}
public function isAdmin(): bool
{
return $this->role === 'ADMIN';
}
public function isTourGuide(): bool
{
return $this->role === 'TOUR GUIDE';
}
public function isMember(): bool
{
return in_array($this->role, ['MEMBER', 'TOUR GUIDE'], true);
}
/** Darf Touren anlegen (Admin oder Tour Guide). */
public function canCreateTours(): bool
{
return $this->isAdmin() || $this->isTourGuide();
}
}