Skip to content

Commit 809f22b

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 809f22b

3 files changed

Lines changed: 189 additions & 0 deletions

File tree

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

Lines changed: 40 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,12 @@ 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+
// symfony/type-info < 7.4.20 resolves its keyless items to a single '' key, which is left to that branch too.
250+
if ($type instanceof ArrayShapeType && !array_is_list($shape = $type->getShape()) && !isset($shape[''])) {
251+
return $this->applyNullability($this->getArrayShapeSchema($type, $readableLink), $isNullable);
252+
}
253+
247254
if ($type instanceof CollectionType) {
248255
$valueType = $type->getCollectionValueType();
249256
$valueSchema = $this->getJsonSchemaFromType($valueType, $readableLink);
@@ -300,6 +307,39 @@ private function getJsonSchemaFromType(Type $type, ?bool $readableLink = null):
300307
return ['type' => Schema::UNKNOWN_TYPE];
301308
}
302309

310+
/**
311+
* @return array<string, mixed>
312+
*/
313+
private function getArrayShapeSchema(ArrayShapeType $type, ?bool $readableLink): array
314+
{
315+
$properties = [];
316+
$required = [];
317+
318+
foreach ($type->getShape() as $key => ['type' => $valueType, 'optional' => $optional]) {
319+
$valueSchema = $this->getJsonSchemaFromType($valueType, $readableLink);
320+
$properties[(string) $key] = [] === $valueSchema ? new \ArrayObject() : $valueSchema;
321+
322+
if (!$optional) {
323+
$required[] = (string) $key;
324+
}
325+
}
326+
327+
$schema = ['type' => 'object', 'properties' => $properties];
328+
329+
// An empty "required" is invalid in OpenAPI 3.0
330+
if ($required) {
331+
$schema['required'] = $required;
332+
}
333+
334+
if ($type->isSealed()) {
335+
$schema['additionalProperties'] = false;
336+
} elseif (null !== ($extraValueType = $type->getExtraValueType()) && [] !== ($extraSchema = $this->getJsonSchemaFromType($extraValueType, $readableLink))) {
337+
$schema['additionalProperties'] = $extraSchema;
338+
}
339+
340+
return $schema;
341+
}
342+
303343
/**
304344
* Gets the JSON Schema definition for a class.
305345
*/
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
$report = new self();
39+
$report->totals = ['total' => 0, 'processed' => 0];
40+
$report->unsealed = ['name' => ''];
41+
$report->tuple = [0, ''];
42+
43+
return $report;
44+
}
45+
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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+
use Symfony\Component\TypeInfo\Type;
21+
use Symfony\Component\TypeInfo\Type\ArrayShapeType;
22+
use Symfony\Component\TypeInfo\TypeIdentifier;
23+
use Symfony\Component\TypeInfo\TypeResolver\StringTypeResolver;
24+
25+
final class JsonSchemaArrayShapeTest extends ApiTestCase
26+
{
27+
use SetupClassResourcesTrait;
28+
29+
protected static ?bool $alwaysBootKernel = false;
30+
31+
private SchemaFactoryInterface $schemaFactory;
32+
33+
protected function setUp(): void
34+
{
35+
parent::setUp();
36+
$this->schemaFactory = self::getContainer()->get('api_platform.json_schema.schema_factory');
37+
}
38+
39+
/**
40+
* @return class-string[]
41+
*/
42+
public static function getResources(): array
43+
{
44+
return [Issue8766Report::class];
45+
}
46+
47+
public function testArrayShapeDescribesItsKeys(): void
48+
{
49+
$this->assertEquals(new \ArrayObject([
50+
'type' => 'object',
51+
'properties' => [
52+
'total' => ['type' => 'integer'],
53+
'processed' => ['type' => 'integer'],
54+
'failed' => ['type' => ['integer', 'null']],
55+
],
56+
'required' => ['processed', 'total'],
57+
'additionalProperties' => false,
58+
]), $this->properties()['totals']);
59+
}
60+
61+
public function testUnsealedArrayShapeAllowsExtraKeys(): void
62+
{
63+
if (!Type::arrayShape([], false, Type::string(), Type::int())->getExtraValueType()?->isIdentifiedBy(TypeIdentifier::INT)) {
64+
$this->markTestSkipped('symfony/type-info < 7.4.6 returns the extra key type from ArrayShapeType::getExtraValueType().');
65+
}
66+
67+
$this->assertEquals(new \ArrayObject([
68+
'type' => 'object',
69+
'properties' => [
70+
'name' => ['type' => 'string'],
71+
],
72+
'required' => ['name'],
73+
'additionalProperties' => ['type' => 'integer'],
74+
]), $this->properties()['unsealed']);
75+
}
76+
77+
public function testListArrayShapeStaysAnArray(): void
78+
{
79+
// symfony/type-info < 7.4.20 merges keyless items into one '' key, the tuple then falls back to a map
80+
$tuple = (new StringTypeResolver())->resolve('array{int, string}');
81+
if ($tuple instanceof ArrayShapeType && !array_is_list($tuple->getShape())) {
82+
$this->assertArrayNotHasKey('properties', $this->properties()['tuple']);
83+
84+
return;
85+
}
86+
87+
$this->assertEquals(new \ArrayObject([
88+
'type' => 'array',
89+
'items' => [
90+
'anyOf' => [
91+
['type' => 'integer'],
92+
['type' => 'string'],
93+
],
94+
],
95+
]), $this->properties()['tuple']);
96+
}
97+
98+
private function properties(): array
99+
{
100+
$schema = $this->schemaFactory->buildSchema(Issue8766Report::class, 'json');
101+
102+
return (array) $schema->getDefinitions()['Issue8766Report']['properties'];
103+
}
104+
}

0 commit comments

Comments
 (0)