Files
2026-03-08 22:58:56 +08:00

119 lines
3.5 KiB
PHP

<?php
namespace app\repository;
use app\model\EctUser;
use app\repository\bean\User;
use app\flow\exception\IllegalUsageException;
use app\repository\exception\ResultNotAsExpectedException;
use support\Model;
class UserRepository extends BaseRepository
{
public function __construct(){
$this->model = new EctUser();
}
/**
* @param int $user_id
* @return User
* @throws IllegalUsageException
*/
public function getUser(int $user_id): User
{
$result = EctUser::where('user_id', $user_id)->first();
if ($result === null) throw new IllegalUsageException();
return new User($result->user_id, $result->user_name, $result->role_id, $result->department_id, $result->user_rfid);
}
/**
* 返回用户的rfid
*/
public function getRfid(User $user): string
{
return EctUser::where('user_id', $user->user_id)->first();
}
/**
* 根据用户名返回用户
* @param string $name
* @return array<User>
* @throws IllegalUsageException
*/
public function getUserByName(string $name): array
{
$list = [];
$ectUsers = EctUser::where('user_name', $name)->get();
if ($ectUsers === null) throw new IllegalUsageException();
foreach ($ectUsers as $ectUser) {
$list[] = new User($ectUser->user_id, $ectUser->user_name, $ectUser->role_id, $ectUser->department_id, $ectUser->user_rfid);
}
return $list;
}
/**
* @param int $id
* @return array<User>
* @throws IllegalUsageException
*/
public function getUserById(int $id): array
{
$ectUsers = EctUser::where('user_id', $id)->first();
if ($ectUsers === null) throw new IllegalUsageException();
$list = [];
foreach ($ectUsers as $ectUser) {
$list[] = new User($ectUser->user_id, $ectUser->user_name, $ectUser->role_id, $ectUser->department_id, $ectUser->user_rfid);
}
return $list;
}
/**
* @return array<User> 用户列表
*/
public function getAll(): array
{
$list = [];
$all = EctUser::all();
foreach ($all as $user) {
$list[] = new User($user->user_id, $user->user_name, $user->role_id, $user->department_id, $user->user_rfid);
}
return $list;
}
/**
* 根据 RFID 卡号查询操作员(人员卡识别用)
*
* @param string $rfid RFID 卡号(自动转大写匹配)
* @return EctUser|null 找到返回模型,找不到返回 null
* @throws ResultNotAsExpectedException
*/
public function findByRfid(string $rfid): ?EctUser
{
$rfid = strtoupper($rfid);
$isAllDigit = ctype_digit($rfid);
$rfids = EctUser::where(function ($query) use ($rfid, $isAllDigit) {
$query->where('user_rfid', $rfid)
->orWhere('rfid3', $rfid);
if ($isAllDigit) {
$rfidWithoutZero = ltrim($rfid, '0');
$rfidWithoutZero = $rfidWithoutZero === '' ? '0' : $rfidWithoutZero;
$query->orWhere('user_rfid', $rfidWithoutZero)
->orWhere('rfid3', $rfidWithoutZero);
}
})->distinct()
->get();
// 如果数量不对就抛出异常
if (count($rfids) > 1 || count($rfids) == 0) {
throw new ResultNotAsExpectedException("RFID Conflict, rfid {$rfid} count: " . count($rfids));
}
return $rfids[0];
}
public static function new(): BaseRepository
{
return new self();
}
}