Skip to content

Commit 8b7d363

Browse files
committed
Use schema provided example data for example const
1 parent b5cb6c3 commit 8b7d363

File tree

3 files changed

+22
-10
lines changed

3 files changed

+22
-10
lines changed

src/Gatherer/Property.php

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ public static function gather(
1818
SchemaRegistry $schemaRegistry,
1919
): \ApiClients\Tools\OpenApiClientGenerator\Representation\Property {
2020
$exampleData = null;
21+
22+
if (count($property->examples ?? []) > 0) {
23+
$exampleData = $property->examples[count($property->examples) === 1 ? 0 : mt_rand(0, count($property->examples) - 1)];
24+
} else if ($property->example !== null) {
25+
$exampleData = $property->example;
26+
}
27+
2128
$propertyName = str_replace([
2229
'@',
2330
'+',
@@ -83,14 +90,16 @@ public static function gather(
8390
$schemaRegistry,
8491
)
8592
);
86-
$exampleData = $type->payload->example;
93+
$exampleData = ($exampleData ?? []) + $type->payload->example;
8794
} else {
88-
if ($type === 'int') {
89-
$exampleData = 13;
90-
} elseif ($type === 'bool') {
91-
$exampleData = false;
92-
} else {
93-
$exampleData = 'generated_' . $propertyName;
95+
if ($exampleData === null) {
96+
if ($type === 'int') {
97+
$exampleData = 13;
98+
} elseif ($type === 'bool') {
99+
$exampleData = false;
100+
} else {
101+
$exampleData = 'generated_' . $propertyName;
102+
}
94103
}
95104
$type = new PropertyType(
96105
'scalar',

src/Gatherer/Schema.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public static function gather(
2020
}
2121

2222
$properties = [];
23-
$example = [];
23+
$example = $schema->example ?? [];
2424
foreach ($schema->properties as $propertyName => $property) {
2525
$gatheredProperty = Property::gather(
2626
$className,
@@ -30,7 +30,10 @@ public static function gather(
3030
$schemaRegistry
3131
);
3232
$properties[] = $gatheredProperty;
33-
$example[$gatheredProperty->name] = $gatheredProperty->exampleData;
33+
34+
if (!array_key_exists($gatheredProperty->name, $example)) {
35+
$example[$gatheredProperty->name] = $gatheredProperty->exampleData;
36+
}
3437
}
3538
return new \ApiClients\Tools\OpenApiClientGenerator\Representation\Schema(
3639
$className,

src/Generator/Schema.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public static function generate(string $namespace, \ApiClients\Tools\OpenApiClie
7272
[
7373
new Node\Const_(
7474
'SCHEMA_EXAMPLE_DATA',
75-
(new BuilderFactory)->val($schema->example),
75+
$factory->val(json_encode($schema->example)),
7676
),
7777
],
7878
Class_::MODIFIER_PUBLIC

0 commit comments

Comments
 (0)