|
1
|
|
|
<?php declare(strict_types = 1); |
|
2
|
|
|
/* |
|
3
|
|
|
* This file is part of the KleijnWeb\PhpApi\Descriptions package. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
namespace KleijnWeb\PhpApi\Descriptions\Description\Schema; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* @author John Kleijn <[email protected]> |
|
12
|
|
|
*/ |
|
13
|
|
|
class SchemaFactory |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var array |
|
17
|
|
|
*/ |
|
18
|
|
|
private $schemas = []; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var array |
|
22
|
|
|
*/ |
|
23
|
|
|
private $definitions = []; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @param \stdClass|null $definition |
|
27
|
|
|
* |
|
28
|
|
|
* @return Schema |
|
29
|
|
|
*/ |
|
30
|
|
|
public function create(\stdClass $definition = null): Schema |
|
31
|
|
|
{ |
|
32
|
|
|
if (!$definition) { |
|
33
|
|
|
$definition = (object)[]; |
|
34
|
|
|
$definition->type = Schema::TYPE_ANY; |
|
35
|
|
|
} |
|
36
|
|
|
if (!isset($definition->type)) { |
|
37
|
|
|
$definition = clone $definition; |
|
38
|
|
|
$definition->type = Schema::TYPE_STRING; |
|
39
|
|
|
} |
|
40
|
|
|
if (isset($definition->properties)) { |
|
41
|
|
|
$definition->type = 'object'; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
$index = array_search($definition, $this->definitions); |
|
45
|
|
|
|
|
46
|
|
|
if (false === $index) { |
|
47
|
|
|
|
|
48
|
|
|
if ($definition->type == Schema::TYPE_OBJECT) { |
|
49
|
|
|
$propertySchemas = (object)[]; |
|
50
|
|
|
|
|
51
|
|
|
foreach (isset($definition->properties) ? $definition->properties : [] as $attributeName => $propertyDefinition) { |
|
52
|
|
|
$propertySchemas->$attributeName = $this->create($propertyDefinition); |
|
53
|
|
|
} |
|
54
|
|
|
$schema = new ObjectSchema($definition, $propertySchemas); |
|
55
|
|
|
} elseif ($definition->type == Schema::TYPE_ARRAY) { |
|
56
|
|
|
$itemsSchema = isset($definition->items) ? $this->create($definition->items) : null; |
|
57
|
|
|
$schema = new ArraySchema($definition, $itemsSchema); |
|
58
|
|
|
} else { |
|
59
|
|
|
$schema = new ScalarSchema($definition); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
$this->definitions[] = $definition; |
|
63
|
|
|
$this->schemas[] = $schema; |
|
64
|
|
|
|
|
65
|
|
|
return $schema; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $this->schemas[$index]; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|