-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidatableTrait.php
37 lines (33 loc) · 1.09 KB
/
ValidatableTrait.php
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
<?php
/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <[email protected]>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*
*/
namespace Koded\Http;
use Koded\Http\Interfaces\{HttpInputValidator, HttpStatus, Response};
use Koded\Stdlib\{Data, Immutable};
use function Koded\Stdlib\json_serialize;
/**
* @method Response|null getParsedBody
*/
trait ValidatableTrait
{
public function validate(HttpInputValidator $validator, Data &$input = null): ?Response
{
$input = new Immutable($this->getParsedBody() ?? []);
if (0 === $input->count()) {
$errors = ['validate' => 'Nothing to validate', 'code' => HttpStatus::BAD_REQUEST];
return new ServerResponse(json_serialize($errors), HttpStatus::BAD_REQUEST);
}
if (empty($errors = $validator->validate($input))) {
return null;
}
$errors['status'] = (int)($errors['status'] ?? HttpStatus::BAD_REQUEST);
return new ServerResponse(json_serialize($errors), $errors['status']);
}
}