diff --git a/src/Validator/BindForm.php b/src/Validator/BindForm.php index c825625..a404671 100644 --- a/src/Validator/BindForm.php +++ b/src/Validator/BindForm.php @@ -39,7 +39,7 @@ class BindForm implements InjectParameterInterface if (!class_exists($attribute->getName())) { continue; } - $rule = inject($attribute->newInstance()); + $rule = \inject($attribute->newInstance()); if ($rule instanceof ValidatorInterface) { $validator->addRule($property->getName(), $rule); } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 68bbdb0..e3c369c 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -51,7 +51,10 @@ class Validator */ public function addRule(string $name, ValidatorInterface $rule): void { - $this->rules[$name] = $rule; + if (!isset($this->rules[$name])) { + $this->rules[$name] = []; + } + $this->rules[$name][] = $rule; } @@ -71,7 +74,7 @@ class Validator $type = new \ReflectionProperty($this->formData, $key); if (!($type->getType() instanceof \ReflectionUnionType)) { $value = match ($type->getType()?->getName()) { - 'int' => (int)$value, + 'int' => (int)$value, 'float' => (float)$value, default => $value }; @@ -93,8 +96,10 @@ class Validator public function run(ServerRequestInterface|Request $request): bool { foreach ($this->rules as $name => $rule) { - if (!$rule->dispatch($this->formData, $name)) { - return $this->addError($name); + foreach ($rule as $item) { + if (!$item->dispatch($this->formData, $name)) { + return $this->addError($name); + } } } return true; @@ -107,7 +112,7 @@ class Validator */ private function addError($field): bool { - $this->message = $field . ' error'; + $this->message = 'Field ' . $field . ' param format fail.'; return false; } diff --git a/src/Validator/ValidatorMiddleware.php b/src/Validator/ValidatorMiddleware.php index 80b0133..68e3fc5 100644 --- a/src/Validator/ValidatorMiddleware.php +++ b/src/Validator/ValidatorMiddleware.php @@ -37,7 +37,7 @@ class ValidatorMiddleware implements MiddlewareInterface { $validator = $this->validator->bindData($request); if (!$validator->run($request)) { - return $this->response->html('400 Bad Request', 400); + return $this->response->html($validator->error(), 415); } else { return $handler->handle($request); }