1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\JsonGuard; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* A Reference object represents an internal $ref in a JSON object. |
7
|
|
|
* Because JSON references can be circular, in-lining the reference is |
8
|
|
|
* impossible. This object can be substituted for the $ref instead, |
9
|
|
|
* allowing lazy resolution of the $ref when needed. |
10
|
|
|
*/ |
11
|
|
|
class Reference implements \JsonSerializable |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* A JSON object resulting from a json_decode call. |
15
|
|
|
* |
16
|
|
|
* @var object |
17
|
|
|
*/ |
18
|
|
|
private $schema; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* A valid JSON reference. The reference should point to a location in $schema. |
22
|
|
|
* @see https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 |
23
|
|
|
* |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
private $ref; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param object $schema |
30
|
|
|
* @param string $ref |
31
|
|
|
*/ |
32
|
28 |
|
public function __construct($schema, $ref) |
33
|
|
|
{ |
34
|
28 |
|
$this->schema = $schema; |
35
|
28 |
|
$this->ref = $ref; |
36
|
28 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Specify data which should be serialized to JSON. |
40
|
|
|
* Because a reference can be circular, references are always |
41
|
|
|
* re-serialized as the reference property instead of attempting |
42
|
|
|
* to inline the data. |
43
|
|
|
* |
44
|
|
|
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
45
|
|
|
* @return mixed data which can be serialized by <b>json_encode</b>, |
46
|
|
|
* which is a value of any type other than a resource. |
47
|
|
|
*/ |
48
|
4 |
|
public function jsonSerialize() |
49
|
|
|
{ |
50
|
4 |
|
return ['$ref' => $this->ref]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Resolve the reference and return the data. |
55
|
|
|
* |
56
|
|
|
* @return mixed |
57
|
|
|
*/ |
58
|
28 |
|
public function resolve() |
59
|
|
|
{ |
60
|
28 |
|
$path = trim($this->ref, '#'); |
61
|
28 |
|
$pointer = new Pointer($this->schema); |
62
|
28 |
|
return $pointer->get($path); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Proxies property access to the underlying schema. |
67
|
|
|
* |
68
|
|
|
* @param string $property |
69
|
|
|
* @return mixed |
70
|
|
|
* @throws \InvalidArgumentException |
71
|
|
|
*/ |
72
|
2 |
|
public function __get($property) |
73
|
|
|
{ |
74
|
2 |
|
$schema = $this->resolve(); |
75
|
2 |
|
if (isset($schema->$property)) { |
76
|
2 |
|
return $schema->$property; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
throw new \InvalidArgumentException(sprintf('Unknown property "%s"', $property)); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|