From 8b7d363a84ff048dea8d99ff0079c4d695c20178 Mon Sep 17 00:00:00 2001 From: Cees-Jan Kiewiet Date: Mon, 27 Feb 2023 10:25:02 +0100 Subject: [PATCH] Use schema provided example data for example const --- src/Gatherer/Property.php | 23 ++++++++++++++++------- src/Gatherer/Schema.php | 7 +++++-- src/Generator/Schema.php | 2 +- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/Gatherer/Property.php b/src/Gatherer/Property.php index f28fbd1..05a521f 100644 --- a/src/Gatherer/Property.php +++ b/src/Gatherer/Property.php @@ -18,6 +18,13 @@ public static function gather( SchemaRegistry $schemaRegistry, ): \ApiClients\Tools\OpenApiClientGenerator\Representation\Property { $exampleData = null; + + if (count($property->examples ?? []) > 0) { + $exampleData = $property->examples[count($property->examples) === 1 ? 0 : mt_rand(0, count($property->examples) - 1)]; + } else if ($property->example !== null) { + $exampleData = $property->example; + } + $propertyName = str_replace([ '@', '+', @@ -83,14 +90,16 @@ public static function gather( $schemaRegistry, ) ); - $exampleData = $type->payload->example; + $exampleData = ($exampleData ?? []) + $type->payload->example; } else { - if ($type === 'int') { - $exampleData = 13; - } elseif ($type === 'bool') { - $exampleData = false; - } else { - $exampleData = 'generated_' . $propertyName; + if ($exampleData === null) { + if ($type === 'int') { + $exampleData = 13; + } elseif ($type === 'bool') { + $exampleData = false; + } else { + $exampleData = 'generated_' . $propertyName; + } } $type = new PropertyType( 'scalar', diff --git a/src/Gatherer/Schema.php b/src/Gatherer/Schema.php index bf50c41..9dbb04f 100644 --- a/src/Gatherer/Schema.php +++ b/src/Gatherer/Schema.php @@ -20,7 +20,7 @@ public static function gather( } $properties = []; - $example = []; + $example = $schema->example ?? []; foreach ($schema->properties as $propertyName => $property) { $gatheredProperty = Property::gather( $className, @@ -30,7 +30,10 @@ public static function gather( $schemaRegistry ); $properties[] = $gatheredProperty; - $example[$gatheredProperty->name] = $gatheredProperty->exampleData; + + if (!array_key_exists($gatheredProperty->name, $example)) { + $example[$gatheredProperty->name] = $gatheredProperty->exampleData; + } } return new \ApiClients\Tools\OpenApiClientGenerator\Representation\Schema( $className, diff --git a/src/Generator/Schema.php b/src/Generator/Schema.php index 8eeada8..6d5d1b9 100644 --- a/src/Generator/Schema.php +++ b/src/Generator/Schema.php @@ -72,7 +72,7 @@ public static function generate(string $namespace, \ApiClients\Tools\OpenApiClie [ new Node\Const_( 'SCHEMA_EXAMPLE_DATA', - (new BuilderFactory)->val($schema->example), + $factory->val(json_encode($schema->example)), ), ], Class_::MODIFIER_PUBLIC