Skip to content

Commit 4d023b2

Browse files
committed
Add example data constant to schema
1 parent a7cc5bc commit 4d023b2

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

src/Generator/Schema.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,69 @@ public static function generate(string $name, string $namespace, string $classNa
4545

4646
$class = $factory->class($className)->makeFinal()->addStmt(
4747
$schemaJson
48+
)->addStmt(
49+
new Node\Stmt\ClassConst(
50+
[
51+
new Node\Const_(
52+
'SCHEMA_EXAMPLE',
53+
new Node\Scalar\String_(
54+
json_encode((function (array $schema): array {
55+
$iterate = function (array $schema) use (&$iterate): array {
56+
$examples = [];
57+
58+
if (!array_key_exists('properties', $schema)) {
59+
return $examples;
60+
}
61+
foreach ($schema['properties'] as $propertyName => $property) {
62+
if (
63+
array_key_exists('type', $property) &&
64+
$property['type'] === 'object' &&
65+
array_key_exists('properties', $property) &&
66+
$property['properties'] !== null
67+
) {
68+
$examples[$propertyName] = $iterate($property);
69+
if (count($examples[$propertyName]) === 0) {
70+
unset($examples[$propertyName]);
71+
}
72+
continue;
73+
}
74+
75+
if (
76+
array_key_exists('type', $property) &&
77+
$property['type'] === 'array' &&
78+
array_key_exists('items', $property) &&
79+
$property['items'] !== null &&
80+
array_key_exists('type', $property['items']) &&
81+
$property['items']['type'] === 'object'
82+
) {
83+
$items = $iterate($property['items']);
84+
85+
if (count($items) > 0) {
86+
$examples[$propertyName] = [$items];
87+
}
88+
continue;
89+
}
90+
91+
if (array_key_exists('examples', $property)) {
92+
$examples[$propertyName] = $property['examples'][count($property['examples']) === 1 ? 0 : mt_rand(0, count($property['examples']) - 1)];
93+
} else if (
94+
array_key_exists('example', $property) &&
95+
$property['example'] !== null
96+
) {
97+
$examples[$propertyName] = $property['example'];
98+
}
99+
}
100+
101+
return $examples;
102+
};
103+
104+
return $iterate($schema);
105+
})(json_decode(json_encode($schema->getSerializableData()), true)))
106+
)
107+
),
108+
],
109+
Class_::MODIFIER_PUBLIC
110+
)
48111
)->addStmt(
49112
new Node\Stmt\ClassConst(
50113
[

0 commit comments

Comments
 (0)