> */ protected array $rules = []; /** * @var string */ protected string $message = ''; /** * @var object */ protected object $formData; /** * @var array */ protected array $alias = []; /** * @var array */ protected array $ignoring = []; /** * @var array */ protected array $types = []; /** * @param object $formData * @return object */ public function setFormData(object $formData): object { $this->formData = $formData; return $formData; } /** * @return object */ public function getFormData(): object { return $this->formData; } /** * @param string $alias * @param string $property * @return void */ public function setAlias(string $alias, string $property): void { $this->alias[$alias] = $property; } /** * @param string $name * @param array $rule * @return void */ public function addRule(string $name, array $rule): void { if (!isset($this->rules[$name])) { $this->rules[$name] = []; } foreach ($rule as $item) { $isFirst = array_pop($item); $dispatch = count($item) > 1 ? $item : [$item[0], 'dispatch']; if ($isFirst) { array_unshift($this->rules[$name], $dispatch); } else { $this->rules[$name][] = $dispatch; } } } /** * @param RequestInterface|ServerRequestInterface|ConstrictRequest $request * @return bool * @throws */ public function run(RequestInterface|ServerRequestInterface|ConstrictRequest $request): bool { $params = !$request->isPost() ? $request->getQueryParams() : $request->getParsedBody(); foreach ($this->rules as $name => $rules) { /** @var array> $typeValidator */ $typeValidator = array_pop($rules); if (!isset($params[$name])) { if (isset($rules[0])) { if ($rules[0][0] instanceof RequiredValidatorFilter) { return $this->addError('The request field ' . $name . ' is mandatory and indispensable'); } } } if (!call_user_func($typeValidator, $this->formData, $name, $params[$name] ?? null)) { return $this->addError('The parameter type used in the request field ' . $name . ' is incorrect'); } /** @var array $rule */ foreach ($rules as $rule) { if (!call_user_func($rule, $this->formData->{$name})) { return $this->addError('Request field ' . $name . ' value format error'); } } } return true; } /** * @param $field * @return bool */ private function addError($field): bool { $this->message = $field; return false; } /** * @return string */ public function error(): string { return $this->message; } }