| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace App\Module\Pet\Validators;
- use App\Module\Pet\Services\PetStealService;
- use App\Module\Farm\Models\FarmCrop;
- use UCore\Validator;
- /**
- * 宠物偷菜验证器
- *
- * 用于验证宠物偷菜操作是否有效
- */
- class PetStealValidator extends Validator
- {
- /**
- * 验证偷菜操作
- *
- * @param mixed $value 作物ID (plantId)
- * @param array $data 包含用户ID等信息的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $plantId = (int)$value;
- // 从 args 获取字段键名
- $stealerIdKey = $this->args[0] ?? 'user_id'; // 偷菜者用户ID键名
- $targetUserIdKey = $this->args[1] ?? 'userId'; // 被偷者用户ID键名
- $stealerId = $data[$stealerIdKey] ?? null;
- $targetUserId = $data[$targetUserIdKey] ?? null;
- if (!$stealerId) {
- $this->addError('偷菜者用户ID不能为空');
- return false;
- }
- if (!$targetUserId) {
- $this->addError('被偷者用户ID不能为空');
- return false;
- }
- try {
- // 通过作物ID获取作物信息
- $crop = FarmCrop::find($plantId);
- if (!$crop) {
- $this->addError("作物{$plantId}不存在");
- return false;
- }
- // 获取土地ID
- $landId = $crop->land_id;
- // 检查作物是否属于目标用户
- if ($crop->user_id != $targetUserId) {
- $this->addError("作物{$plantId}属于用户{$crop->user_id},不属于目标用户{$targetUserId}");
- return false;
- }
- // 使用PetStealService检查是否可以偷菜
- $canStealResult = PetStealService::canSteal($stealerId, $targetUserId, $landId);
- if (!$canStealResult['can_steal']) {
- $this->addError($canStealResult['reason']);
- return false;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('偷菜验证过程发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|