-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonArrayLoader.php
64 lines (60 loc) · 1.96 KB
/
JsonArrayLoader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
namespace JsonRef;
use JsonRef\Uri;
use JsonRef\JsonLoader;
use JsonRef\Exception\ResourceNotFoundException;
/**
* Simple JsonLoader wrapper over an array of preloaded schemas.
* This provides a way to load "packed" schemas, packed according to this ~pseudo standard approach.
*/
class JsonArrayLoader extends JsonLoader
{
private $schemaMap;
/**
* Construct by parsing $schemas array. Entries can be either JSON document strings or 2-tuples: [$uri, $schema]
* where $schema is a string or \StdObject instance.
* @input $schemas array of schemas.
*/
public function __construct(array $schemas = []) {
foreach($schemas as $i => $schema) {
$uri = null;
if(is_array($schema)) {
[$uri, $schema] = $schema;
}
if($uri) {
$uri = new Uri($uri);
}
if(!$uri && is_string($schema)) {
$schema = json_decode($schema);
if($schema === null) {
throw new JsonDecodeException(json_last_error());
}
}
if(!$uri && is_object($schema)) {
$refProp = $schema->{'$refProp'} ?? '$id';
$uri = new Uri($schema->$refProp);
}
if(!$uri || !$uri->isAbsoluteUri()) {
throw new \LogicException("Could not resolve URI to identify schema at index $i.");
}
if(!is_object($schema) && !is_string($schema)) {
throw new \LogicException("Invalid schema for URI $uri.");
}
var_dump($uri, $this->schemaMap);
if(isset($this->schemaMap[$uri.""])) {
throw new \LogicException("Schema identified by '$uri' already exists.");
}
$this->schemaMap[$uri.""] = $schema;
}
}
/**
* Load raw data from $uri. The data returned should be a JSON doc decodable with json_decode().
* @throws ResourceNotFoundException.
*/
public function load($uri) {
if(!isset($this->schemaMap[$uri.""])) {
throw new ResourceNotFoundException("Could not load resource $uri.");
}
return $this->schemaMap[$uri.""];
}
}