SeedOwnershipValidator.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\GameItems\Services\ItemService;
  4. use UCore\Validator;
  5. /**
  6. * 种子归属验证器
  7. *
  8. * 验证用户是否拥有指定的种子
  9. */
  10. class SeedOwnershipValidator extends Validator
  11. {
  12. /**
  13. * 验证种子归属
  14. *
  15. * @param mixed $value 物品ID
  16. * @param array $data 包含用户ID和实例ID的数组
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. $itemId = (int)$value;
  22. // 从 args 获取参数键名
  23. $userIdKey = $this->args[0] ?? 'user_id';
  24. $instanceIdKey = $this->args[1] ?? 'item_instance_id';
  25. $userId = $data[$userIdKey] ?? null;
  26. $instanceId = $data[$instanceIdKey] ?? null;
  27. if (!$userId) {
  28. $this->addError('用户ID不能为空');
  29. return false;
  30. }
  31. try {
  32. // 检查用户是否拥有该种子
  33. $userItems = ItemService::getUserItems($userId, ['item_id' => $itemId]);
  34. if ($userItems->isEmpty()) {
  35. $this->addError('您没有该种子');
  36. return false;
  37. }
  38. // 如果指定了实例ID,检查特定实例
  39. if ($instanceId > 0) {
  40. $userItem = ItemService::getUserItem($userId, $itemId, $instanceId);
  41. if (!$userItem) {
  42. $this->addError('指定的种子实例不存在');
  43. return false;
  44. }
  45. if ($userItem->quantity <= 0) {
  46. $this->addError('种子数量不足');
  47. return false;
  48. }
  49. } else {
  50. // 检查总数量
  51. $totalQuantity = $userItems->sum('quantity');
  52. if ($totalQuantity <= 0) {
  53. $this->addError('种子数量不足');
  54. return false;
  55. }
  56. }
  57. return true;
  58. } catch (\Exception $e) {
  59. $this->addError('验证种子归属时发生错误: ' . $e->getMessage());
  60. return false;
  61. }
  62. }
  63. }