Completed
Push — master ( 993520...f97157 )
by Dawid
06:13
created

JsonSchemaValidatorFactory::getValidator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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