SchemaLoader::load()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 31
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 15
c 2
b 0
f 0
nc 4
nop 1
dl 0
loc 31
ccs 19
cts 19
cp 1
crap 4
rs 9.7666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Usox\JsonSchemaApi\Dispatch;
6
7
use stdClass;
8
use Teapot\StatusCode\Http;
9
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaInvalidException;
10
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotFoundException;
11
use Usox\JsonSchemaApi\Dispatch\Exception\SchemaNotLoadableException;
12
13
/**
14
 * Lookup the schema and load its contents
15
 */
16
final class SchemaLoader implements SchemaLoaderInterface
17
{
18
    /**
19
     * Loads and returns the schema content
20
     *
21
     * @throws SchemaInvalidException
22
     * @throws SchemaNotFoundException
23
     * @throws SchemaNotLoadableException
24
     */
25 4
    public function load(
26
        string $schemaFilePath,
27
    ): stdClass {
28 4
        if (!file_exists($schemaFilePath)) {
29 1
            throw new SchemaNotFoundException(
30 1
                sprintf('Schema file `%s` not found', $schemaFilePath),
31 1
                Http::INTERNAL_SERVER_ERROR,
32 1
            );
33
        }
34
35 3
        $fileContent = @file_get_contents($schemaFilePath);
36
37 3
        if ($fileContent === false) {
38 1
            throw new SchemaNotLoadableException(
39 1
                sprintf('Schema file `%s` not loadable', $schemaFilePath),
40 1
                Http::INTERNAL_SERVER_ERROR,
41 1
            );
42
        }
43
44
        // Load the methods schema
45 2
        $methodSchemaContent = json_decode($fileContent);
46
47 2
        if (json_last_error() !== JSON_ERROR_NONE) {
48 1
            throw new SchemaInvalidException(
49 1
                sprintf('Schema does not contain valid json (%s)', json_last_error_msg()),
50 1
                Http::INTERNAL_SERVER_ERROR,
51 1
            );
52
        }
53
54
        /** @var stdClass $methodSchemaContent */
55 1
        return $methodSchemaContent;
56
    }
57
}
58