Passed
Push — master ( cce2e1...993520 )
by Dawid
02:22
created

JsonSchemaValidatorFactory::createSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
ccs 9
cts 9
cp 1
rs 9.4285
cc 1
eloc 9
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiechu\SymfonyCommonsBundle\Service;
6
7
use JsonSchema\SchemaStorage;
8
use JsonSchema\Uri\UriRetriever;
9
use JsonSchema\Validator;
10
use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException;
11
12
class JsonSchemaValidatorFactory extends AbstractSchemaValidatorFactory
13
{
14
    /**
15
     * @param string $id
16
     *
17
     * @throws FileLocatorFileNotFoundException
18
     * @throws \InvalidArgumentException
19
     * @throws \RuntimeException
20
     *
21
     * @return JsonSchemaValidator
22
     */
23 2
    public function getValidator(string $id): JsonSchemaValidator
24
    {
25 2
        $this->assertHasSchema($id);
26
27 2
        if (!$this->registeredSchemas[$id] instanceof JsonSchemaValidator) {
28 2
            $this->registeredSchemas[$id] = new JsonSchemaValidator($this->createSchema($id), new Validator());
29
        }
30
31 2
        return $this->registeredSchemas[$id];
32
    }
33
34
    /**
35
     * @param string $id
36
     *
37
     * @throws \InvalidArgumentException
38
     * @throws FileLocatorFileNotFoundException
39
     *
40
     * @return \stdClass
41
     */
42 2
    protected function createSchema(string $id): \stdClass
43
    {
44 2
        $mainSchemaFilePath = $this->fileLocator->locate($this->registeredSchemas[$id]);
45 2
        $schemaUri = basename($mainSchemaFilePath);
46 2
        $schemaBaseUri = sprintf('file://%s/%s', dirname($mainSchemaFilePath), $schemaUri);
47
48 2
        $retriever = new UriRetriever();
49 2
        $schema = $retriever->retrieve($schemaUri, $schemaBaseUri);
50
51 2
        $schemaStorage = new SchemaStorage($retriever);
52 2
        $schemaStorage->addSchema($schemaBaseUri, $schema);
53
54 2
        return $schema;
55
    }
56
}
57