1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace RoundingWell\Schematic; |
4
|
|
|
|
5
|
|
|
abstract class Schema |
6
|
|
|
{ |
7
|
|
|
protected const SCHEMA_TYPES = [ |
8
|
|
|
'array', |
9
|
|
|
'boolean', |
10
|
|
|
'integer', |
11
|
|
|
'null', |
12
|
|
|
'number', |
13
|
|
|
'object', |
14
|
|
|
'string' |
15
|
|
|
]; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param string $path |
19
|
|
|
* @return static |
20
|
|
|
*/ |
21
|
2 |
|
public static function fromFile($path): Schema |
22
|
|
|
{ |
23
|
2 |
|
return self::make(json_decode(file_get_contents($path))); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param object $json |
28
|
|
|
*/ |
29
|
11 |
|
public static function make($json): Schema |
30
|
|
|
{ |
31
|
11 |
|
if ( ! isset($json->type)) { |
32
|
1 |
|
throw new \InvalidArgumentException('Missing schema type.'); |
33
|
|
|
} |
34
|
|
|
|
35
|
10 |
|
if ( ! in_array(strtolower($json->type), self::SCHEMA_TYPES)) { |
36
|
1 |
|
throw new \InvalidArgumentException(sprintf( |
37
|
1 |
|
'No schema type available for %s.', |
38
|
1 |
|
$json->type |
39
|
|
|
)); |
40
|
|
|
} |
41
|
|
|
|
42
|
9 |
|
$schema = 'RoundingWell\\Schematic\\Schema\\' . ucfirst($json->type) . 'Schema'; |
43
|
|
|
|
44
|
9 |
|
return new $schema($json); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @var object |
49
|
|
|
*/ |
50
|
|
|
protected $schema; |
51
|
|
|
|
52
|
9 |
|
public function __construct($schema) |
53
|
|
|
{ |
54
|
9 |
|
$this->schema = $schema; |
55
|
9 |
|
} |
56
|
|
|
|
57
|
9 |
|
public function type(): string |
58
|
|
|
{ |
59
|
9 |
|
return $this->schema->type; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
abstract public function phpType(): string; |
63
|
|
|
|
64
|
3 |
|
public function isArray(): bool |
65
|
|
|
{ |
66
|
3 |
|
return $this->type() === 'array'; |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
public function isBoolean(): bool |
70
|
|
|
{ |
71
|
1 |
|
return $this->type() === 'boolean'; |
72
|
|
|
} |
73
|
|
|
|
74
|
2 |
|
public function isInteger(): bool |
75
|
|
|
{ |
76
|
2 |
|
return $this->type() === 'integer'; |
77
|
|
|
} |
78
|
|
|
|
79
|
2 |
|
public function isNull(): bool |
80
|
|
|
{ |
81
|
2 |
|
return $this->type() === 'null'; |
82
|
|
|
} |
83
|
|
|
|
84
|
1 |
|
public function isNumber(): bool |
85
|
|
|
{ |
86
|
1 |
|
return $this->type() === 'number'; |
87
|
|
|
} |
88
|
|
|
|
89
|
3 |
|
public function isObject(): bool |
90
|
|
|
{ |
91
|
3 |
|
return $this->type() === 'object'; |
92
|
|
|
} |
93
|
|
|
|
94
|
3 |
|
public function isString(): bool |
95
|
|
|
{ |
96
|
3 |
|
return $this->type() === 'string'; |
97
|
|
|
} |
98
|
|
|
|
99
|
1 |
|
public function title(): string |
100
|
|
|
{ |
101
|
1 |
|
return $this->schema->title ?? ''; |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|