| Total Complexity | 5 |
| Total Lines | 46 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 16 | final readonly class SchemaValidator implements SchemaValidatorInterface |
||
|
|
|||
| 17 | { |
||
| 18 | 4 | public function __construct( |
|
| 19 | private Validator $validator |
||
| 20 | ) { |
||
| 21 | 4 | } |
|
| 22 | |||
| 23 | /** |
||
| 24 | * @return TBody&array |
||
| 25 | * |
||
| 26 | * @throws ValidatorException |
||
| 27 | */ |
||
| 28 | 4 | public function getValidatedBody( |
|
| 29 | ServerRequestInterface $request, |
||
| 30 | string $schemaFileName |
||
| 31 | ): array { |
||
| 32 | 4 | $schemaFilePath = __DIR__ . '/../../../resource/api-schema/' . $schemaFileName; |
|
| 33 | |||
| 34 | 4 | if (!file_exists($schemaFilePath)) { |
|
| 35 | 1 | throw new ValidatorException( |
|
| 36 | 1 | sprintf('Schema `%s` not found', $schemaFileName) |
|
| 37 | 1 | ); |
|
| 38 | } |
||
| 39 | |||
| 40 | 3 | $body = (string) $request->getBody(); |
|
| 41 | |||
| 42 | 3 | $bodyDecoded = json_decode($body); |
|
| 43 | |||
| 44 | 3 | if (json_last_error() !== JSON_ERROR_NONE) { |
|
| 45 | 1 | throw new ValidatorException( |
|
| 46 | 1 | json_last_error_msg() |
|
| 47 | 1 | ); |
|
| 48 | } |
||
| 49 | |||
| 50 | 2 | $result = $this->validator->validate( |
|
| 51 | 2 | $bodyDecoded, |
|
| 52 | 2 | file_get_contents($schemaFilePath) |
|
| 53 | 2 | ); |
|
| 54 | |||
| 55 | 2 | if (!$result->isValid()) { |
|
| 56 | 1 | throw new ValidatorException( |
|
| 57 | 1 | (string) $result->error()?->message() |
|
| 58 | 1 | ); |
|
| 59 | } |
||
| 60 | |||
| 61 | 1 | return json_decode($body, true, 512, JSON_THROW_ON_ERROR); |
|
| 62 | } |
||
| 64 |