PetVegetealValidation.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. namespace App\Module\AppGame\Validations;
  3. use App\Module\Pet\Validators\PetStealValidator;
  4. use App\Module\Pet\Validators\PetOwnershipValidator;
  5. /**
  6. * 宠物偷菜验证类
  7. *
  8. * 用于验证宠物偷菜请求的参数
  9. */
  10. class PetVegetealValidation extends ValidationBase
  11. {
  12. /**
  13. * 被偷的玩家ID
  14. *
  15. * @var int
  16. */
  17. public int $user_id = 0;
  18. /**
  19. * 宠物ID
  20. *
  21. * @var int
  22. */
  23. public int $pet_id = 0;
  24. /**
  25. * 作物ID (对应land_id)
  26. *
  27. * @var int
  28. */
  29. public int $plant_id = 0;
  30. /**
  31. * 当前用户ID (由系统注入)
  32. *
  33. * @var int
  34. */
  35. public int $current_user_id = 0;
  36. /**
  37. * 使用Protobuf-Message创建验证器,并注入current_user_id
  38. *
  39. * @param \Google\Protobuf\Internal\Message $message
  40. * @param $scene
  41. * @return static
  42. */
  43. public static function makeByProrobufUser(\Google\Protobuf\Internal\Message $message, $scene = ''): static
  44. {
  45. $data = json_decode($message->serializeToJsonString(), true);
  46. // 映射protobuf字段名到验证类字段名
  47. $mappedData = [];
  48. if (isset($data['userId'])) {
  49. $mappedData['user_id'] = $data['userId'];
  50. }
  51. if (isset($data['petId'])) {
  52. $mappedData['pet_id'] = $data['petId'];
  53. }
  54. if (isset($data['plantId'])) {
  55. $mappedData['plant_id'] = $data['plantId'];
  56. }
  57. // 注入当前用户ID
  58. $mappedData['current_user_id'] = \App\Module\AppGame\SessionApp::getUserId();
  59. return new static($mappedData, [], [], $scene);
  60. }
  61. /**
  62. * 验证规则
  63. *
  64. * @param array $rules 自定义规则
  65. * @return array
  66. */
  67. public function rules($rules = []): array
  68. {
  69. return [
  70. [
  71. 'user_id,pet_id,plant_id,current_user_id', 'required'
  72. ],
  73. [
  74. 'user_id,pet_id,plant_id', 'integer', 'min' => 1,
  75. 'msg' => '{attr}必须是大于0的整数'
  76. ],
  77. // 验证宠物归属权和状态
  78. [
  79. 'pet_id', new PetOwnershipValidator($this, ['current_user_id']),
  80. 'msg' => '宠物验证失败'
  81. ],
  82. // 验证偷菜操作是否有效
  83. [
  84. 'plant_id', new PetStealValidator($this, ['current_user_id', 'user_id']),
  85. 'msg' => '偷菜操作验证失败'
  86. ]
  87. ];
  88. }
  89. /**
  90. * 设置默认值
  91. *
  92. * @return array
  93. */
  94. public function default(): array
  95. {
  96. return [];
  97. }
  98. /**
  99. * 字段翻译
  100. *
  101. * @return array
  102. */
  103. public function translates(): array
  104. {
  105. return [
  106. 'user_id' => '被偷玩家ID',
  107. 'pet_id' => '宠物ID',
  108. 'plant_id' => '作物ID',
  109. 'current_user_id' => '当前用户ID',
  110. ];
  111. }
  112. }