This commit is contained in:
xl
2023-11-09 20:45:16 +08:00
parent c3753bbd28
commit d6f6312af9
3 changed files with 12 additions and 7 deletions
+1 -1
View File
@@ -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);
}
+10 -5
View File
@@ -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;
}
+1 -1
View File
@@ -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);
}