123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Rules;
- use Txj\Elastic\Facades\ES;
- use Illuminate\Contracts\Validation\Rule;
- use Illuminate\Support\Facades\Request;
- /**
- * es_exists:table,column:otherColumn,toColumn
- * 验证的字段必须存在于给定的数据库表中.支持多个字段验证,otherColumn为当前其他字段,toColumn需要验证的表的其他字段。
- *
- * Class EsExistsRule
- * @package App\Rules
- */
- class EsExistsRule implements Rule
- {
- protected string $table;
- protected string $siteAliasName;
- protected ?string $params;
- protected ?string $message;
- protected string $attribute;
- protected ?int $ignoreId = 0;
- protected mixed $value;
- /**
- * Create a new rule instance.
- *
- * @return void
- */
- public function __construct(string $table, array $ruleValue = [], $siteAliasName = '')
- {
- $this->table = $table; // 当前的集合表
- $this->siteAliasName = $siteAliasName; // 站点别名
- $this->params = (isset($ruleValue['params']) && !empty($ruleValue['params'])) ? $ruleValue['params'] : '';
- $this->message = (isset($ruleValue['error_msg']) && !empty($ruleValue['error_msg'])) ? $ruleValue['error_msg'] : '';
- }
- /**
- * Determine if the validation rule passes.
- *
- * @param $attribute
- * @param mixed $value
- * @return bool
- */
- public function passes($attribute, $value): bool
- {
- $this->attribute = $attribute;
- $this->value = $value;
- // 支持多个字段条件
- $columnArr = explode(':', $this->params);
- $firstStr = array_shift($columnArr);
- $arr = explode(",", $firstStr);
- $existTable = $arr[0];
- $column = $arr[1];
- $where = [$column => $value];
- if ($columnArr) {
- foreach ($columnArr as $row) {
- $arr = explode(",", $row);
- $otherColumn = $arr[0];
- $toColumn = $arr[1];
- $where = array_merge($where, [$toColumn => Request::input($otherColumn)]);
- }
- }
- $find = ES::table($existTable)->where('is_delete', 0)->where($where);
- try {
- return (bool)$find->count();
- } catch (\Exception $e) {
- $this->message = $e->getMessage();
- return false;
- }
- }
- /**
- * 编辑的时候,过滤掉当前的id
- *
- * @param $id
- * @return $this
- */
- public function ignore($id): EsUniqueRule
- {
- $this->ignoreId = $id;
- return $this;
- }
- /**
- * Get the validation error message.
- *
- * @return string
- */
- public function message()
- {
- return $this->message ?: '该值 :attribute 不存在!';
- }
- }
|