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\HttpKernel\KernelInterface; |
11
|
|
|
|
12
|
|
|
class JsonSchemaValidatorFactory |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var KernelInterface |
16
|
|
|
*/ |
17
|
|
|
protected $kernel; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
protected $registeredSchemas; |
23
|
|
|
|
24
|
1 |
|
public function __construct(KernelInterface $kernel) |
25
|
|
|
{ |
26
|
1 |
|
$this->kernel = $kernel; |
27
|
1 |
|
$this->registeredSchemas = []; |
28
|
1 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @throws \RuntimeException When schema with provided $id is already registered |
32
|
|
|
*/ |
33
|
1 |
|
public function registerSchema(string $id, string $schemaResourceLocation): self |
34
|
|
|
{ |
35
|
1 |
|
if ($this->hasSchema($id)) { |
36
|
|
|
throw new \RuntimeException(sprintf('Schema with id "%s" already registered.', $id)); |
37
|
|
|
} |
38
|
|
|
|
39
|
1 |
|
$this->registeredSchemas[$id] = $schemaResourceLocation; |
40
|
|
|
|
41
|
1 |
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
public function hasSchema(string $id): bool |
45
|
|
|
{ |
46
|
1 |
|
return array_key_exists($id, $this->registeredSchemas); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @throws \RuntimeException |
51
|
|
|
* @throws \InvalidArgumentException |
52
|
|
|
*/ |
53
|
|
|
public function getValidator(string $id): JsonSchemaValidator |
54
|
|
|
{ |
55
|
|
|
if (!$this->hasSchema($id)) { |
56
|
|
|
throw new \RuntimeException(sprintf('Schema with id "%s" is not registered.', $id)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
if (!$this->registeredSchemas[$id] instanceof JsonSchemaValidator) { |
60
|
|
|
$this->registeredSchemas[$id] = new JsonSchemaValidator($this->createSchema($id), new Validator()); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $this->registeredSchemas[$id]; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @throws \RuntimeException |
68
|
|
|
* @throws \InvalidArgumentException |
69
|
|
|
*/ |
70
|
|
|
protected function createSchema(string $id): \stdClass |
71
|
|
|
{ |
72
|
|
|
$mainSchemaFilePath = $this->kernel->locateResource($this->registeredSchemas[$id]); |
73
|
|
|
$schemaUri = basename($mainSchemaFilePath); |
74
|
|
|
$schemaBaseUri = sprintf('file://%s/%s', dirname($mainSchemaFilePath), $schemaUri); |
75
|
|
|
|
76
|
|
|
$retriever = new UriRetriever(); |
77
|
|
|
$schema = $retriever->retrieve($schemaUri, $schemaBaseUri); |
78
|
|
|
|
79
|
|
|
$schemaStorage = new SchemaStorage($retriever); |
80
|
|
|
$schemaStorage->addSchema($schemaBaseUri, $schema); |
81
|
|
|
|
82
|
|
|
return $schema; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|