Code

< 40 %
40-60 %
> 60 %
1
<?php
2
3
/*
4
 * This file is part of the Koded package.
5
 *
6
 * (c) Mihail Binev <[email protected]>
7
 *
8
 * Please view the LICENSE distributed with this source code
9
 * for the full copyright and license information.
10
 *
11
 */
12
13
namespace Koded\Http;
14
15
use Koded\Http\Interfaces\{HttpInputValidator, HttpStatus, Response};
16
use Koded\Stdlib\{Data, Immutable};
17
use function Koded\Stdlib\json_serialize;
18
19
/**
20
 * @method Response|null getParsedBody
21
 */
22
trait ValidatableTrait
23
{
24 4
    public function validate(HttpInputValidator $validator, Data &$input = null): ?Response
25
    {
26 4
        $input = new Immutable($this->getParsedBody() ?? []);
27
        if (0 === $input->count()) {
28 4
            $errors = ['validate' => 'Nothing to validate', 'code' => HttpStatus::BAD_REQUEST];
29 1
            return new ServerResponse(json_serialize($errors), HttpStatus::BAD_REQUEST);
30
        }
31
        if (empty($errors = $validator->validate($input))) {
32 3
            return null;
33 1
        }
34
        $errors['status'] = (int)($errors['status'] ?? HttpStatus::BAD_REQUEST);
35
        return new ServerResponse(json_serialize($errors), $errors['status']);
36 2
    }
37
}
38