Test Setup Failed
Push — master ( f60f99...a79e53 )
by Daniel
02:49
created

RequestValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 45
ccs 20
cts 20
cp 1
rs 10
wmc 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Usox\JsonSchemaApi\Dispatch;
6
7
use Teapot\StatusCode\Http;
8
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaInvalidException;
9
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotFoundException;
10
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotLoadableException;
11
use Opis\JsonSchema\Validator;
12
use Psr\Http\Message\ServerRequestInterface;
13
use stdClass;
14
use Usox\JsonSchemaApi\Dispatch\Exception\JsonInvalidException;
15
use Usox\JsonSchemaApi\Exception\RequestMalformedException;
16
17
/**
18
 * Validates the request against the basic request schema (method name, parameter)
19
 */
20
final readonly class RequestValidator implements RequestValidatorInterface
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 20 at column 6
Loading history...
21
{
22 5
    public function __construct(
23
        private SchemaLoaderInterface $schemaLoader,
24
        private Validator $schemaValidator,
25
    ) {
26 5
    }
27
28
    /**
29
     * @throws SchemaInvalidException
30
     * @throws SchemaNotFoundException
31
     * @throws SchemaNotLoadableException
32
     * @throws JsonInvalidException
33
     * @throws RequestMalformedException
34
     */
35 3
    public function validate(ServerRequestInterface $request): stdClass
36
    {
37
        // Decode the input and load the schema
38 3
        $decodedInput = json_decode($request->getBody()->getContents());
39
40 3
        if (json_last_error() !== JSON_ERROR_NONE) {
41 1
            throw new JsonInvalidException(
42 1
                sprintf('Input is no valid json (%s)', json_last_error_msg()),
43 1
                Http::BAD_REQUEST
44 1
            );
45
        }
46
47 2
        $fileContent = $this->schemaLoader->load(__DIR__ . '/../../dist/request.json');
48
49
        /** @var stdClass $decodedInput */
50
        // First, validate the input against the basic request schema
51 2
        $validationResult = $this->schemaValidator->validate(
52 2
            $decodedInput,
53 2
            $fileContent
54 2
        );
55
56
        // Throw exception if the input does not validate against the basic request schema
57 2
        if (!$validationResult->isValid()) {
58 1
            throw new RequestMalformedException(
59 1
                'Request is invalid',
60 1
                Http::BAD_REQUEST
61 1
            );
62
        }
63
64 1
        return $decodedInput;
65
    }
66
}
67