Completed
Push — v3 ( c94160...3fd6a7 )
by Mihail
06:23
created

ValidatableTrait::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 2
Metric Value
cc 3
eloc 8
c 5
b 0
f 2
nc 3
nop 2
dl 0
loc 12
rs 10
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\Data;
17
use Koded\Stdlib\Immutable;
18
use function Koded\Stdlib\json_serialize;
19
20
/**
21
 * @method Response|null getParsedBody
22
 */
23
trait ValidatableTrait
24
{
25
    public function validate(HttpInputValidator $validator, Data &$input = null): ?Response
26
    {
27
        $input = new Immutable($this->getParsedBody() ?? []);
0 ignored issues
show
Bug introduced by
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

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