Passed
Push — master ( 04bb0b...31510a )
by Daniel
11:10
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 11
cts 11
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 30 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Usox\JsonSchemaApi\Dispatch;
6
7
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaInvalidException;
8
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotFoundException;
9
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotLoadableException;
10
use Opis\JsonSchema\Validator;
11
use Psr\Http\Message\ServerRequestInterface;
12
use stdClass;
13
use Teapot\StatusCode;
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 class RequestValidator implements RequestValidatorInterface
21
{
22 5
    public function __construct(
23
        private SchemaLoaderInterface $schemaLoader,
24
        private Validator $schemaValidator,
25
    ) {
26
    }
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
                StatusCode::BAD_REQUEST
44
            );
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
            $decodedInput,
53
            $fileContent
54
        );
55
56
        // Throw exception if the input does not validate against the basic request schema
57 2
        if ($validationResult->isValid() === false) {
58 1
            throw new RequestMalformedException(
59
                'Request is invalid',
60
                StatusCode::BAD_REQUEST
61
            );
62
        }
63
64 1
        return $decodedInput;
65
    }
66
}
67