EsExistsRule.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace App\Rules;
  3. use Txj\Elastic\Facades\ES;
  4. use Illuminate\Contracts\Validation\Rule;
  5. use Illuminate\Support\Facades\Request;
  6. /**
  7. * es_exists:table,column:otherColumn,toColumn
  8. * 验证的字段必须存在于给定的数据库表中.支持多个字段验证,otherColumn为当前其他字段,toColumn需要验证的表的其他字段。
  9. *
  10. * Class EsExistsRule
  11. * @package App\Rules
  12. */
  13. class EsExistsRule implements Rule
  14. {
  15. protected string $table;
  16. protected string $siteAliasName;
  17. protected ?string $params;
  18. protected ?string $message;
  19. protected string $attribute;
  20. protected ?int $ignoreId = 0;
  21. protected mixed $value;
  22. /**
  23. * Create a new rule instance.
  24. *
  25. * @return void
  26. */
  27. public function __construct(string $table, array $ruleValue = [], $siteAliasName = '')
  28. {
  29. $this->table = $table; // 当前的集合表
  30. $this->siteAliasName = $siteAliasName; // 站点别名
  31. $this->params = (isset($ruleValue['params']) && !empty($ruleValue['params'])) ? $ruleValue['params'] : '';
  32. $this->message = (isset($ruleValue['error_msg']) && !empty($ruleValue['error_msg'])) ? $ruleValue['error_msg'] : '';
  33. }
  34. /**
  35. * Determine if the validation rule passes.
  36. *
  37. * @param $attribute
  38. * @param mixed $value
  39. * @return bool
  40. */
  41. public function passes($attribute, $value): bool
  42. {
  43. $this->attribute = $attribute;
  44. $this->value = $value;
  45. // 支持多个字段条件
  46. $columnArr = explode(':', $this->params);
  47. $firstStr = array_shift($columnArr);
  48. $arr = explode(",", $firstStr);
  49. $existTable = $arr[0];
  50. $column = $arr[1];
  51. $where = [$column => $value];
  52. if ($columnArr) {
  53. foreach ($columnArr as $row) {
  54. $arr = explode(",", $row);
  55. $otherColumn = $arr[0];
  56. $toColumn = $arr[1];
  57. $where = array_merge($where, [$toColumn => Request::input($otherColumn)]);
  58. }
  59. }
  60. $find = ES::table($existTable)->where('is_delete', 0)->where($where);
  61. try {
  62. return (bool)$find->count();
  63. } catch (\Exception $e) {
  64. $this->message = $e->getMessage();
  65. return false;
  66. }
  67. }
  68. /**
  69. * 编辑的时候,过滤掉当前的id
  70. *
  71. * @param $id
  72. * @return $this
  73. */
  74. public function ignore($id): EsUniqueRule
  75. {
  76. $this->ignoreId = $id;
  77. return $this;
  78. }
  79. /**
  80. * Get the validation error message.
  81. *
  82. * @return string
  83. */
  84. public function message()
  85. {
  86. return $this->message ?: '该值 :attribute 不存在!';
  87. }
  88. }