Completed
Pull Request — master (#14)
by Mihail
01:45
created

ValidatableTrait.php (1 issue)

Labels
Severity
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, Response};
16
use Koded\Stdlib\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): ?Response
25
    {
26 4
        $body = new Immutable($this->getParsedBody() ?? []);
0 ignored issues
show
It seems like $this->getParsedBody() ?? array() can also be of type Koded\Http\Interfaces\Response; however, parameter $values of Koded\Stdlib\Immutable::__construct() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

26
        $body = new Immutable(/** @scrutinizer ignore-type */ $this->getParsedBody() ?? []);
Loading history...
27
28 4
        if (0 === $body->count()) {
29 1
            return null;
30
        }
31
32 3
        if (empty($errors = $validator->validate($body))) {
33 1
            return null;
34
        }
35
36 2
        $errors['code'] = (int)($errors['code'] ?? StatusCode::BAD_REQUEST);
37 2
        return new ServerResponse(json_serialize($errors), $errors['code']);
38
    }
39
}
40