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
|
|
|
|