Files
kiri-router/src/Validator/Validator.php
T

110 lines
1.7 KiB
PHP
Raw Normal View History

2023-04-15 23:29:27 +08:00
<?php
2023-04-16 01:24:30 +08:00
declare(strict_types=1);
2023-04-15 23:29:27 +08:00
2023-04-15 23:31:16 +08:00
namespace Kiri\Router\Validator;
2023-04-15 23:29:27 +08:00
2023-04-15 23:31:16 +08:00
use Kiri\Router\Interface\ValidatorInterface;
2023-04-16 00:06:10 +08:00
use Kiri\Router\Request;
2023-04-15 23:31:16 +08:00
use Psr\Http\Message\ServerRequestInterface;
2023-04-15 23:29:27 +08:00
class Validator
{
/**
* @var ValidatorInterface[]
*/
private array $rules = [];
private string $message;
2023-04-15 23:31:16 +08:00
private object $formData;
2023-04-16 03:51:18 +08:00
/**
* @param object $formData
*/
public function setFormData(object $formData): void
{
$this->formData = $formData;
}
/**
* @return object
*/
public function getFormData(): object
{
return $this->formData;
}
2023-04-15 23:29:27 +08:00
/**
* @param string $name
* @param ValidatorInterface $rule
* @return void
*/
2023-04-16 03:51:18 +08:00
public function addRule(string $name, ValidatorInterface $rule): void
2023-04-15 23:29:27 +08:00
{
$this->rules[$name] = $rule;
2023-04-15 23:31:16 +08:00
}
/**
2023-04-16 00:06:10 +08:00
* @param ServerRequestInterface|Request $request
2023-04-15 23:31:16 +08:00
* @return Validator
*/
2023-04-16 00:06:10 +08:00
public function bindData(ServerRequestInterface|Request $request): static
2023-04-15 23:31:16 +08:00
{
if ($request->isPost) {
$data = $request->getParsedBody();
} else {
$data = $request->getQueryParams();
}
foreach ($data as $key => $value) {
2023-04-16 14:04:00 +08:00
if (property_exists($this->formData, $key)) {
2023-04-15 23:31:16 +08:00
$this->formData->{$key} = $value;
}
}
return $this;
2023-04-15 23:29:27 +08:00
}
/**
2023-04-16 14:47:12 +08:00
* @param ServerRequestInterface|Request $request
2023-04-15 23:29:27 +08:00
* @return bool
*/
2023-04-16 14:47:12 +08:00
public function run(ServerRequestInterface|Request $request): bool
2023-04-15 23:29:27 +08:00
{
foreach ($this->rules as $name => $rule) {
2023-04-15 23:31:16 +08:00
if (!$rule->dispatch($this->formData, $name)) {
2023-04-15 23:29:27 +08:00
return false;
}
}
return true;
}
/**
* @param $field
* @return bool
*/
private function addError($field): bool
{
$this->message = $field . ' error';
return false;
}
/**
* @return string
*/
public function error(): string
{
return $this->message;
}
}