Passed
Push — main ( b3043b...2a9756 )
by Daniel
04:51
created

SchemaValidator::getValidatedBody()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 34
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 34
ccs 16
cts 16
cp 1
rs 9.7333
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Api\Lib;
6
7
use Opis\JsonSchema\Validator;
8
use Psr\Http\Message\ServerRequestInterface;
9
10
/**
11
 * @template TBody
12
 *
13
 * @implements SchemaValidatorInterface<TBody>
14
 */
15
final class SchemaValidator implements SchemaValidatorInterface
16
{
17 4
    public function __construct(
18
        private readonly Validator $validator
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 18 at column 25
Loading history...
19
    ) {
20
    }
21
22
    /**
23
     * @return TBody&array
24
     *
25
     * @throws Exception\ValidatorException
26
     */
27 4
    public function getValidatedBody(
28
        ServerRequestInterface $request,
29
        string $schemaFileName
30
    ): array {
31 4
        $schemaFilePath = __DIR__ . '/../../../resource/api-schema/' . $schemaFileName;
32
33 4
        if (!file_exists($schemaFilePath)) {
34 1
            throw new Exception\ValidatorException(
35 1
                sprintf('Schema `%s` not found', $schemaFileName)
36
            );
37
        }
38
39 3
        $body = (string) $request->getBody();
40
41 3
        $bodyDecoded = json_decode($body);
42
43 3
        if (json_last_error() !== JSON_ERROR_NONE) {
44 1
            throw new Exception\ValidatorException(
45 1
                json_last_error_msg()
46
            );
47
        }
48
49 2
        $result = $this->validator->validate(
50
            $bodyDecoded,
51 2
            file_get_contents($schemaFilePath)
52
        );
53
54 2
        if (!$result->isValid()) {
55 1
            throw new Exception\ValidatorException(
56 1
                (string) $result->error()?->message()
57
            );
58
        }
59
60 1
        return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
61
    }
62
}
63