Files
FendxPHP/app/Service/UserService.php

199 lines
5.6 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Service;
use Fendx\Core\Annotation\Service;
use Fendx\Core\Annotation\Inject;
use Fendx\Db\Annotation\Transactional;
use Fendx\Cache\Annotation\Cacheable;
use Fendx\Cache\Annotation\CacheUpdate;
use Fendx\Cache\Annotation\CacheEvict;
use App\Dao\UserDao;
use App\Entity\User;
use Fendx\Web\Validator\Validator;
use Fendx\Common\Exception\BusinessException;
#[Service]
class UserService
{
#[Inject]
private UserDao $userDao;
#[Cacheable(key: "user:{id}", ttl: 3600)]
public function getUser(int $id): ?User
{
return $this->userDao->findById($id);
}
public function getUserByEmail(string $email): ?User
{
return $this->userDao->findByEmail($email);
}
public function getUserByUsername(string $username): ?User
{
return $this->userDao->findByUsername($username);
}
#[Cacheable(key: "users:active", ttl: 1800)]
public function getActiveUsers(): array
{
return $this->userDao->findAllActive();
}
public function getUsersPaginated(int $page = 1, int $pageSize = 10): array
{
return $this->userDao->findPaginated($page, $pageSize);
}
#[Transactional]
#[CacheUpdate(key: "user:{id}")]
public function createUser(array $data): User
{
// 验证数据
$this->validateUserData($data);
// 检查邮箱和用户名是否已存在
if ($this->userDao->findByEmail($data['email'])) {
throw new BusinessException(400, 'Email already exists');
}
if ($this->userDao->findByUsername($data['username'])) {
throw new BusinessException(400, 'Username already exists');
}
// 加密密码
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
return $this->userDao->create($data);
}
#[Transactional]
#[CacheUpdate(key: "user:{id}")]
public function updateUser(int $id, array $data): bool
{
$user = $this->userDao->findById($id);
if (!$user) {
throw new BusinessException(404, 'User not found');
}
// 如果更新邮箱,检查是否已存在
if (isset($data['email']) && $data['email'] !== $user->email) {
if ($this->userDao->findByEmail($data['email'])) {
throw new BusinessException(400, 'Email already exists');
}
}
// 如果更新用户名,检查是否已存在
if (isset($data['username']) && $data['username'] !== $user->username) {
if ($this->userDao->findByUsername($data['username'])) {
throw new BusinessException(400, 'Username already exists');
}
}
// 如果更新密码,需要加密
if (isset($data['password'])) {
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
}
return $this->userDao->update($id, $data);
}
#[Transactional]
#[CacheEvict(key: "user:{id}")]
public function deleteUser(int $id): bool
{
$user = $this->userDao->findById($id);
if (!$user) {
throw new BusinessException(404, 'User not found');
}
return $this->userDao->delete($id);
}
public function searchUsers(string $keyword, int $page = 1, int $pageSize = 10): array
{
return $this->userDao->search($keyword, $page, $pageSize);
}
public function getUsersCount(): int
{
return $this->userDao->count();
}
public function getActiveUsersCount(): int
{
return $this->userDao->countActive();
}
public function validatePassword(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
public function changePassword(int $userId, string $oldPassword, string $newPassword): bool
{
$user = $this->userDao->findById($userId);
if (!$user) {
throw new BusinessException(404, 'User not found');
}
if (!$this->validatePassword($oldPassword, $user->password)) {
throw new BusinessException(400, 'Invalid old password');
}
return $this->updateUser($userId, ['password' => $newPassword]);
}
public function toggleUserStatus(int $id): bool
{
$user = $this->userDao->findById($id);
if (!$user) {
throw new BusinessException(404, 'User not found');
}
$newStatus = $user->status === 1 ? 0 : 1;
return $this->updateUser($id, ['status' => $newStatus]);
}
private function validateUserData(array $data): void
{
$validator = Validator::make($data, [
'username' => 'required|min:3|max:50',
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (!$validator->validate()) {
throw new BusinessException(422, 'Validation failed', $validator->errors());
}
}
public function validateUserUpdateData(array $data): void
{
$rules = [];
if (isset($data['username'])) {
$rules['username'] = 'required|min:3|max:50';
}
if (isset($data['email'])) {
$rules['email'] = 'required|email';
}
if (isset($data['password'])) {
$rules['password'] = 'required|min:6';
}
if (!empty($rules)) {
$validator = Validator::make($data, $rules);
if (!$validator->validate()) {
throw new BusinessException(422, 'Validation failed', $validator->errors());
}
}
}
}