Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1340,7 +1340,8 @@ jobs:
tests/Fixtures/app/console api:openapi:export --yaml -o build/out/openapi/openapi_v3.yaml
- name: Validate OpenAPI documents
run: |
npx @quobix/vacuum lint -r tests/Fixtures/app/ruleset.yaml build/out/openapi/openapi_v3.yaml -d --ignore-array-circle-ref --ignore-polymorph-circle-ref -b --no-clip
npm i -g @quobix/vacuum
vacuum lint -r tests/Fixtures/app/ruleset.yaml build/out/openapi/openapi_v3.yaml -d --ignore-array-circle-ref --ignore-polymorph-circle-ref -b --no-clip

laravel:
name: Laravel (PHP ${{ matrix.php }})
Expand Down
16 changes: 15 additions & 1 deletion src/Hydra/JsonSchema/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareI
use SchemaUriPrefixTrait;

private const ITEM_BASE_SCHEMA_NAME = 'HydraItemBaseSchema';
private const ITEM_WITHOUT_ID_BASE_SCHEMA_NAME = 'HydraItemBaseSchemaWithoutId';
private const COLLECTION_BASE_SCHEMA_NAME = 'HydraCollectionBaseSchema';

private const BASE_PROP = [
'type' => 'string',
];
Expand Down Expand Up @@ -68,9 +70,16 @@ final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareI
],
],
] + self::BASE_PROPS,
];

private const ITEM_BASE_SCHEMA_WITH_ID = self::ITEM_BASE_SCHEMA + [
'required' => ['@id', '@type'],
];

private const ITEM_BASE_SCHEMA_WITHOUT_ID = self::ITEM_BASE_SCHEMA + [
'required' => ['@type'],
];

/**
* @var array<string, true>
*/
Expand Down Expand Up @@ -144,10 +153,15 @@ public function buildSchema(string $className, string $format = 'jsonld', string
return $schema;
}

$hasNoId = Schema::TYPE_OUTPUT === $type && false === ($serializerContext['gen_id'] ?? true);
$baseName = self::ITEM_BASE_SCHEMA_NAME;

if ($hasNoId) {
$baseName = self::ITEM_WITHOUT_ID_BASE_SCHEMA_NAME;
}

if (!isset($definitions[$baseName])) {
$definitions[$baseName] = self::ITEM_BASE_SCHEMA;
$definitions[$baseName] = $hasNoId ? self::ITEM_BASE_SCHEMA_WITHOUT_ID : self::ITEM_BASE_SCHEMA_WITH_ID;
}

$allOf = new \ArrayObject(['allOf' => [
Expand Down
4 changes: 4 additions & 0 deletions src/JsonSchema/DefinitionNameFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ public function create(string $className, string $format = 'json', ?string $inpu
$name = $groups ? \sprintf('%s-%s', $prefix, implode('_', $groups)) : $prefix;
}

if (false === ($serializerContext['gen_id'] ?? true)) {
$name .= '_noid';
}

return $this->encodeDefinitionName($name);
}

Expand Down
40 changes: 19 additions & 21 deletions src/JsonSchema/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -245,23 +245,20 @@ private function buildLegacyPropertySchema(Schema $schema, string $definitionNam
}

$subSchemaFactory = $this->schemaFactory ?: $this;
$subSchema = $subSchemaFactory->buildSchema($className, $format, $parentType, null, $subSchema, $serializerContext + [self::FORCE_SUBSCHEMA => true], false);
$subSchema = $subSchemaFactory->buildSchema(
$className,
$format,
$parentType,
null,
$subSchema,
$serializerContext + [self::FORCE_SUBSCHEMA => true, 'gen_id' => $propertyMetadata->getGenId() ?? true],
false,
);

if (!isset($subSchema['$ref'])) {
continue;
}

if (false === $propertyMetadata->getGenId()) {
$subDefinitionName = $this->definitionNameFactory->create($className, $format, $className, null, $serializerContext);

if (isset($subSchema->getDefinitions()[$subDefinitionName])) {
// @see https://github.com/api-platform/core/issues/7162
// Need to rebuild the definition without @id property and set it back to the sub-schema
$subSchemaDefinition = $subSchema->getDefinitions()[$subDefinitionName]->getArrayCopy();
unset($subSchemaDefinition['properties']['@id']);
$subSchema->getDefinitions()[$subDefinitionName] = new \ArrayObject($subSchemaDefinition);
}
}

if ($isCollection) {
$key = ($propertySchema['type'] ?? null) === 'object' ? 'additionalProperties' : 'items';
$propertySchema[$key]['$ref'] = $subSchema['$ref'];
Expand Down Expand Up @@ -371,18 +368,19 @@ private function buildPropertySchema(Schema $schema, string $definitionName, str
$subSchemaInstance = new Schema($version);
$subSchemaInstance->setDefinitions($schema->getDefinitions());
$subSchemaFactory = $this->schemaFactory ?: $this;
$subSchemaResult = $subSchemaFactory->buildSchema($className, $format, $parentType, null, $subSchemaInstance, $serializerContext + [self::FORCE_SUBSCHEMA => true], false);
$subSchemaResult = $subSchemaFactory->buildSchema(
$className,
$format,
$parentType,
null,
$subSchemaInstance,
$serializerContext + [self::FORCE_SUBSCHEMA => true, 'gen_id' => $propertyMetadata->getGenId() ?? true],
false,
);
if (!isset($subSchemaResult['$ref'])) {
continue;
}

if (false === $propertyMetadata->getGenId()) {
$subDefinitionName = $this->definitionNameFactory->create($className, $format, $className, null, $serializerContext);
if (isset($subSchemaResult->getDefinitions()[$subDefinitionName]['properties']['@id'])) {
unset($subSchemaResult->getDefinitions()[$subDefinitionName]['properties']['@id']);
}
}

if ($isCollection) {
$key = ($propertySchema['type'] ?? null) === 'object' ? 'additionalProperties' : 'items';
if (!isset($propertySchema['type'])) {
Expand Down
3 changes: 3 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/AggregateRating.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use Symfony\Component\Serializer\Attribute\Groups;

#[ApiResource(types: 'https://schema.org/AggregateRating', operations: [])]
final class AggregateRating
{
public function __construct(
#[Groups(['with_aggregate_rating'])]
#[ApiProperty(iris: ['https://schema.org/ratingValue'])]
public float $ratingValue,
#[Groups(['with_aggregate_rating'])]
#[ApiProperty(iris: ['https://schema.org/reviewCount'])]
public int $reviewCount,
) {
Expand Down
9 changes: 9 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use Symfony\Component\Serializer\Attribute\Groups;

#[Get(
types: ['https://schema.org/Product'],
Expand All @@ -23,12 +25,19 @@
provider: [self::class, 'provide'],
jsonStream: true
)]
#[GetCollection(
types: ['https://schema.org/Product'],
uriTemplate: '/json-stream-products',
provider: [self::class, 'provide'],
normalizationContext: ['groups' => ['with_aggregate_rating'], 'hydra_prefix' => false]
)]
class Product
{
#[ApiProperty(identifier: true)]
public string $code;

#[ApiProperty(genId: false, iris: ['https://schema.org/aggregateRating'])]
#[Groups(['with_aggregate_rating'])]
public AggregateRating $aggregateRating;

#[ApiProperty(property: 'name', iris: ['https://schema.org/name'])]
Expand Down
1 change: 1 addition & 0 deletions tests/Fixtures/app/ruleset.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
extends: [[spectral:oas, recommended]]
rules:
camel-case-properties: false
circular-references: false
operation-success-response: false
oas3-parameter-description: false
Expand Down
11 changes: 11 additions & 0 deletions tests/Functional/JsonSchema/JsonSchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@
use ApiPlatform\JsonSchema\SchemaFactoryInterface;
use ApiPlatform\Metadata\Operation\Factory\OperationMetadataFactoryInterface;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use ApiPlatform\Symfony\Bundle\Test\Constraint\MatchesJsonSchema;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\AggregateRating;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue5452\Book;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue5501\BrokenDocs;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Issue5501\Related;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\Product;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\ResourceWithEnumProperty;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue5793\BagOfTests;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Issue5793\TestEntity;
Expand Down Expand Up @@ -61,6 +64,8 @@ public static function getResources(): array
Book::class,
JsonSchemaResource::class,
JsonSchemaResourceRelated::class,
Product::class,
AggregateRating::class,
];
}

Expand Down Expand Up @@ -212,4 +217,10 @@ public function testReadOnlySchema(): void
$schema = $this->schemaFactory->buildSchema(JsonSchemaResource::class, 'json', Schema::TYPE_OUTPUT);
$this->assertTrue($schema['definitions']['Resource']['properties']['resourceRelated']['readOnly'] ?? false);
}

public function testGenIdFalse()
{
$schema = $this->schemaFactory->buildSchema(Product::class, 'jsonld', Schema::TYPE_OUTPUT, $this->operationMetadataFactory->create('_api_/json-stream-products_get_collection'));
$this->assertThat(['member' => [['aggregateRating' => ['ratingValue' => '1.0', 'reviewCount' => 1]]]], new MatchesJsonSchema($schema));
}
}
3 changes: 2 additions & 1 deletion tests/JsonSchema/Command/JsonSchemaGenerateCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,14 @@ public function testBackedEnumExamplesAreNotLost(): void

/**
* Test feature #6716.
* Note: in this test the embed object is not a resource, the behavior is different from where the embeded is an ApiResource.
*/
public function testGenId(): void
{
$this->tester->run(['command' => 'api:json-schema:generate', 'resource' => 'ApiPlatform\Tests\Fixtures\TestBundle\Entity\DisableIdGeneration', '--type' => 'output', '--format' => 'jsonld']);
$result = $this->tester->getDisplay();
$json = json_decode($result, associative: true);
$this->assertArrayNotHasKey('@id', $json['definitions']['DisableIdGenerationItem.jsonld']['properties']);
$this->assertArrayNotHasKey('@id', $json['definitions']['DisableIdGenerationItem.jsonld_noid']['properties']);
}

#[DataProvider('arrayPropertyTypeSyntaxProvider')]
Expand Down
Loading