Issues (6)

src/Dispatch/RequestValidator.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Usox\JsonSchemaApi\Dispatch;
6
7
use Opis\JsonSchema\Validator;
8
use Psr\Http\Message\ServerRequestInterface;
9
use stdClass;
10
use Teapot\StatusCode\Http;
11
use Usox\JsonSchemaApi\Dispatch\Exception\JsonInvalidException;
12
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaInvalidException;
13
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotFoundException;
14
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotLoadableException;
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
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