| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace App\Module\Pet\Validators;
- use App\Module\Pet\Models\PetUser;
- use App\Module\Pet\Enums\PetStatus;
- use UCore\Validator;
- /**
- * 宠物归属权和状态验证器
- *
- * 用于验证宠物是否属于指定用户且状态为空闲
- */
- class PetOwnershipValidator extends Validator
- {
- /**
- * 验证宠物归属权和状态
- *
- * @param mixed $value 宠物ID
- * @param array $data 包含用户ID等信息的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $petId = (int)$value;
- if ($petId <= 0) {
- $this->addError('宠物ID必须大于0');
- return false;
- }
- // 从 args 获取用户ID字段键名
- $userIdKey = $this->args[0] ?? 'current_user_id';
- $userId = $data[$userIdKey] ?? null;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- try {
- // 查找宠物
- $pet = PetUser::where('id', $petId)
- ->where('user_id', $userId)
- ->first();
- if (!$pet) {
- $this->addError('宠物不存在或不属于当前用户');
- return false;
- }
- // 检查宠物状态是否为正常(空闲)
- if ($pet->status !== PetStatus::NORMAL) {
- $statusName = match($pet->status) {
- PetStatus::FIGHTING => '战斗中',
- PetStatus::DEAD => '死亡',
- PetStatus::FEEDING => '喂养中',
- PetStatus::TRAINING => '训练中',
- PetStatus::RESTING => '休息中',
- PetStatus::TRAVELING => '外出中',
- default => '未知状态'
- };
- $this->addError("宠物当前状态为{$statusName},无法执行操作");
- return false;
- }
- // 检查宠物体力是否足够(偷菜需要至少20体力)
- if ($pet->stamina < 20) {
- $this->addError('宠物体力不足,至少需要20点体力');
- return false;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('宠物验证过程发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|