From 4d023b278c0600f373f70171b06528980ccb2e10 Mon Sep 17 00:00:00 2001 From: Cees-Jan Kiewiet Date: Mon, 6 Feb 2023 09:47:03 +0100 Subject: [PATCH] Add example data constant to schema --- src/Generator/Schema.php | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/Generator/Schema.php b/src/Generator/Schema.php index 5278b2b..f3d6dd3 100644 --- a/src/Generator/Schema.php +++ b/src/Generator/Schema.php @@ -45,6 +45,69 @@ public static function generate(string $name, string $namespace, string $classNa $class = $factory->class($className)->makeFinal()->addStmt( $schemaJson + )->addStmt( + new Node\Stmt\ClassConst( + [ + new Node\Const_( + 'SCHEMA_EXAMPLE', + new Node\Scalar\String_( + json_encode((function (array $schema): array { + $iterate = function (array $schema) use (&$iterate): array { + $examples = []; + + if (!array_key_exists('properties', $schema)) { + return $examples; + } + foreach ($schema['properties'] as $propertyName => $property) { + if ( + array_key_exists('type', $property) && + $property['type'] === 'object' && + array_key_exists('properties', $property) && + $property['properties'] !== null + ) { + $examples[$propertyName] = $iterate($property); + if (count($examples[$propertyName]) === 0) { + unset($examples[$propertyName]); + } + continue; + } + + if ( + array_key_exists('type', $property) && + $property['type'] === 'array' && + array_key_exists('items', $property) && + $property['items'] !== null && + array_key_exists('type', $property['items']) && + $property['items']['type'] === 'object' + ) { + $items = $iterate($property['items']); + + if (count($items) > 0) { + $examples[$propertyName] = [$items]; + } + continue; + } + + if (array_key_exists('examples', $property)) { + $examples[$propertyName] = $property['examples'][count($property['examples']) === 1 ? 0 : mt_rand(0, count($property['examples']) - 1)]; + } else if ( + array_key_exists('example', $property) && + $property['example'] !== null + ) { + $examples[$propertyName] = $property['example']; + } + } + + return $examples; + }; + + return $iterate($schema); + })(json_decode(json_encode($schema->getSerializableData()), true))) + ) + ), + ], + Class_::MODIFIER_PUBLIC + ) )->addStmt( new Node\Stmt\ClassConst( [