Skip to content

Commit 786e436

Browse files
committed
feat(jsonschema): describe PHPDoc array shapes as objects
Keyed array shapes such as array{total: int, failed?: int} now generate an object schema with their properties and required keys, instead of a generic map with a union value type. Sealed shapes get additionalProperties: false, unsealed shapes with a value type get it as additionalProperties. List shapes stay arrays. Closes #8766
1 parent 052fc45 commit 786e436

3 files changed

Lines changed: 167 additions & 0 deletions

File tree

‎src/JsonSchema/Metadata/Property/Factory/SchemaPropertyMetadataFactory.php‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use ApiPlatform\Metadata\Util\ResourceClassInfoTrait;
2222
use Ramsey\Uuid\UuidInterface;
2323
use Symfony\Component\TypeInfo\Type;
24+
use Symfony\Component\TypeInfo\Type\ArrayShapeType;
2425
use Symfony\Component\TypeInfo\Type\BuiltinType;
2526
use Symfony\Component\TypeInfo\Type\CollectionType;
2627
use Symfony\Component\TypeInfo\Type\IntersectionType;
@@ -244,6 +245,11 @@ private function getJsonSchemaFromType(Type $type, ?bool $readableLink = null):
244245
return $this->applyNullability(['allOf' => $schemas], $isNullable);
245246
}
246247

248+
// A list shape (array{int, string}) is serialized as a JSON array, so it is left to the CollectionType branch
249+
if ($type instanceof ArrayShapeType && !array_is_list($type->getShape())) {
250+
return $this->applyNullability($this->getArrayShapeSchema($type, $readableLink), $isNullable);
251+
}
252+
247253
if ($type instanceof CollectionType) {
248254
$valueType = $type->getCollectionValueType();
249255
$valueSchema = $this->getJsonSchemaFromType($valueType, $readableLink);
@@ -300,6 +306,39 @@ private function getJsonSchemaFromType(Type $type, ?bool $readableLink = null):
300306
return ['type' => Schema::UNKNOWN_TYPE];
301307
}
302308

309+
/**
310+
* @return array<string, mixed>
311+
*/
312+
private function getArrayShapeSchema(ArrayShapeType $type, ?bool $readableLink): array
313+
{
314+
$properties = [];
315+
$required = [];
316+
317+
foreach ($type->getShape() as $key => ['type' => $valueType, 'optional' => $optional]) {
318+
$valueSchema = $this->getJsonSchemaFromType($valueType, $readableLink);
319+
$properties[(string) $key] = [] === $valueSchema ? new \ArrayObject() : $valueSchema;
320+
321+
if (!$optional) {
322+
$required[] = (string) $key;
323+
}
324+
}
325+
326+
$schema = ['type' => 'object', 'properties' => $properties];
327+
328+
// An empty "required" is invalid in OpenAPI 3.0
329+
if ($required) {
330+
$schema['required'] = $required;
331+
}
332+
333+
if ($type->isSealed()) {
334+
$schema['additionalProperties'] = false;
335+
} elseif (null !== ($extraValueType = $type->getExtraValueType()) && [] !== ($extraSchema = $this->getJsonSchemaFromType($extraValueType, $readableLink))) {
336+
$schema['additionalProperties'] = $extraSchema;
337+
}
338+
339+
return $schema;
340+
}
341+
303342
/**
304343
* Gets the JSON Schema definition for a class.
305344
*/
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue8766;
15+
16+
use ApiPlatform\Metadata\ApiResource;
17+
use ApiPlatform\Metadata\Get;
18+
19+
#[ApiResource(
20+
shortName: 'Issue8766Report',
21+
operations: [new Get(uriTemplate: '/issue8766_reports/{id}', provider: [self::class, 'provide'])],
22+
)]
23+
final class Issue8766Report
24+
{
25+
public int $id = 1;
26+
27+
/** @var array{total: int, processed: int, failed?: int|null} */
28+
public array $totals = [];
29+
30+
/** @var array{name: string, ...<string, int>} */
31+
public array $unsealed = [];
32+
33+
/** @var array{int, string} */
34+
public array $tuple = [];
35+
36+
public static function provide(): self
37+
{
38+
return new self();
39+
}
40+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the API Platform project.
5+
*
6+
* (c) Kévin Dunglas <dunglas@gmail.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
declare(strict_types=1);
13+
14+
namespace ApiPlatform\Tests\Functional\JsonSchema;
15+
16+
use ApiPlatform\JsonSchema\SchemaFactoryInterface;
17+
use ApiPlatform\Test\ApiTestCase;
18+
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue8766\Issue8766Report;
19+
use ApiPlatform\Tests\SetupClassResourcesTrait;
20+
21+
final class JsonSchemaArrayShapeTest extends ApiTestCase
22+
{
23+
use SetupClassResourcesTrait;
24+
25+
protected static ?bool $alwaysBootKernel = false;
26+
27+
private SchemaFactoryInterface $schemaFactory;
28+
29+
protected function setUp(): void
30+
{
31+
parent::setUp();
32+
$this->schemaFactory = self::getContainer()->get('api_platform.json_schema.schema_factory');
33+
}
34+
35+
/**
36+
* @return class-string[]
37+
*/
38+
public static function getResources(): array
39+
{
40+
return [Issue8766Report::class];
41+
}
42+
43+
public function testArrayShapeDescribesItsKeys(): void
44+
{
45+
$this->assertEquals(new \ArrayObject([
46+
'type' => 'object',
47+
'properties' => [
48+
'total' => ['type' => 'integer'],
49+
'processed' => ['type' => 'integer'],
50+
'failed' => ['type' => ['integer', 'null']],
51+
],
52+
'required' => ['processed', 'total'],
53+
'additionalProperties' => false,
54+
]), $this->properties()['totals']);
55+
}
56+
57+
public function testUnsealedArrayShapeAllowsExtraKeys(): void
58+
{
59+
$this->assertEquals(new \ArrayObject([
60+
'type' => 'object',
61+
'properties' => [
62+
'name' => ['type' => 'string'],
63+
],
64+
'required' => ['name'],
65+
'additionalProperties' => ['type' => 'integer'],
66+
]), $this->properties()['unsealed']);
67+
}
68+
69+
public function testListArrayShapeStaysAnArray(): void
70+
{
71+
$this->assertEquals(new \ArrayObject([
72+
'type' => 'array',
73+
'items' => [
74+
'anyOf' => [
75+
['type' => 'integer'],
76+
['type' => 'string'],
77+
],
78+
],
79+
]), $this->properties()['tuple']);
80+
}
81+
82+
private function properties(): array
83+
{
84+
$schema = $this->schemaFactory->buildSchema(Issue8766Report::class, 'json');
85+
86+
return (array) $schema->getDefinitions()['Issue8766Report']['properties'];
87+
}
88+
}

0 commit comments

Comments
 (0)