File size: 1,289 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | <?php
declare(strict_types=1);
namespace Presentation\Validation;
use Psr\Http\Message\ServerRequestInterface;
use Somnambulist\Components\Validation\Factory;
class Validator
{
/**
* @param Factory $factory
* @return void
*/
public function __construct(
private Factory $factory
) {
}
/**
* @param ServerRequestInterface $req
* @param array $rules
* @return void
* @throws ValidationException
*/
public function validateRequest(
ServerRequestInterface $req,
array $rules
): void {
$inputs = json_decode(json_encode($req->getParsedBody()), true) + $_FILES;
$this->validate($inputs, $rules);
}
/**
* @param array $inputs
* @param array $rules
* @return void
* @throws ValidationException
*/
public function validate(array $inputs, array $rules): void
{
$validation = $this->factory->validate($inputs, $rules);
if ($validation->fails()) {;
$messages = $validation->errors()->firstOfAll();
foreach ($messages as $field => $message) {
// Throw exception for the first error
throw new ValidationException($message, $field);
}
}
}
}
|