Files
FendxPHP/app/Dao/UserDao.php

107 lines
2.5 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace App\Dao;
use Fendx\Core\Annotation\Dao;
use App\Entity\User;
use Fendx\Db\ORM\Model;
#[Dao]
class UserDao
{
public function findById(int $id): ?User
{
return User::find($id);
}
public function findByEmail(string $email): ?User
{
return User::where('email', $email)->first();
}
public function findByUsername(string $username): ?User
{
return User::where('username', $username)->first();
}
public function findAllActive(): array
{
return User::where('status', 1)->orderBy('created_at', 'desc')->get();
}
public function findPaginated(int $page = 1, int $pageSize = 10): array
{
$offset = ($page - 1) * $pageSize;
$users = User::orderBy('created_at', 'desc')
->limit($pageSize)
->offset($offset)
->get();
$total = User::count();
return [
'users' => $users,
'total' => $total,
'page' => $page,
'pageSize' => $pageSize,
'totalPages' => ceil($total / $pageSize)
];
}
public function create(array $data): User
{
$data['created_at'] = date('Y-m-d H:i:s');
$data['updated_at'] = date('Y-m-d H:i:s');
return User::create($data);
}
public function update(int $id, array $data): bool
{
$data['updated_at'] = date('Y-m-d H:i:s');
return User::find($id)?->update($data) ?? false;
}
public function delete(int $id): bool
{
return User::find($id)?->delete() ?? false;
}
public function count(): int
{
return User::count();
}
public function countActive(): int
{
return User::where('status', 1)->count();
}
public function search(string $keyword, int $page = 1, int $pageSize = 10): array
{
$offset = ($page - 1) * $pageSize;
$users = User::where('username', 'LIKE', "%{$keyword}%")
->orWhere('email', 'LIKE', "%{$keyword}%")
->orderBy('created_at', 'desc')
->limit($pageSize)
->offset($offset)
->get();
$total = User::where('username', 'LIKE', "%{$keyword}%")
->orWhere('email', 'LIKE', "%{$keyword}%")
->count();
return [
'users' => $users,
'total' => $total,
'page' => $page,
'pageSize' => $pageSize,
'totalPages' => ceil($total / $pageSize)
];
}
}