• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 18223414080

03 Oct 2025 01:18PM UTC coverage: 0.0% (-22.0%) from 21.956%
18223414080

Pull #7397

github

web-flow
Merge 69d085182 into 0b8237918
Pull Request #7397: fix(jsonschema/jsonld): make `@id` and `@type` properties required only in the JSON-LD schema for output

0 of 18 new or added lines in 2 files covered. (0.0%)

12304 existing lines in 405 files now uncovered.

0 of 53965 relevant lines covered (0.0%)

0.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/Hydra/JsonSchema/SchemaFactory.php
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\Hydra\JsonSchema;
15

16
use ApiPlatform\JsonLd\ContextBuilder;
17
use ApiPlatform\JsonLd\Serializer\HydraPrefixTrait;
18
use ApiPlatform\JsonSchema\DefinitionNameFactory;
19
use ApiPlatform\JsonSchema\DefinitionNameFactoryInterface;
20
use ApiPlatform\JsonSchema\ResourceMetadataTrait;
21
use ApiPlatform\JsonSchema\Schema;
22
use ApiPlatform\JsonSchema\SchemaFactoryAwareInterface;
23
use ApiPlatform\JsonSchema\SchemaFactoryInterface;
24
use ApiPlatform\JsonSchema\SchemaUriPrefixTrait;
25
use ApiPlatform\Metadata\Operation;
26
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
27

28
/**
29
 * Decorator factory which adds Hydra properties to the JSON Schema document.
30
 *
31
 * @author Kévin Dunglas <dunglas@gmail.com>
32
 */
33
final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareInterface
34
{
35
    use HydraPrefixTrait;
36
    use ResourceMetadataTrait;
37
    use SchemaUriPrefixTrait;
38

39
    private const ITEM_BASE_SCHEMA_NAME = 'HydraItemBaseSchema';
40
    private const ITEM_BASE_SCHEMA_OUTPUT_NAME = 'HydraOutputBaseSchema';
41
    private const COLLECTION_BASE_SCHEMA_NAME = 'HydraCollectionBaseSchema';
42
    private const BASE_PROP = [
43
        'type' => 'string',
44
    ];
45
    private const BASE_PROPS = [
46
        '@id' => self::BASE_PROP,
47
        '@type' => self::BASE_PROP,
48
    ];
49
    private const ITEM_BASE_SCHEMA = [
50
        'type' => 'object',
51
        'properties' => [
52
            '@context' => [
53
                'oneOf' => [
54
                    ['type' => 'string'],
55
                    [
56
                        'type' => 'object',
57
                        'properties' => [
58
                            '@vocab' => [
59
                                'type' => 'string',
60
                            ],
61
                            'hydra' => [
62
                                'type' => 'string',
63
                                'enum' => [ContextBuilder::HYDRA_NS],
64
                            ],
65
                        ],
66
                        'required' => ['@vocab', 'hydra'],
67
                        'additionalProperties' => true,
68
                    ],
69
                ],
70
            ],
71
        ] + self::BASE_PROPS,
72
    ];
73

74
    private const ITEM_BASE_SCHEMA_OUTPUT = [
75
        'required' => ['@id', '@type'],
76
    ] + self::ITEM_BASE_SCHEMA;
77

78
    /**
79
     * @var array<string, true>
80
     */
81
    private array $transformed = [];
82

83
    /**
84
     * @param array<string, mixed> $defaultContext
85
     */
86
    public function __construct(
87
        private readonly SchemaFactoryInterface $schemaFactory,
88
        private readonly array $defaultContext = [],
89
        private ?DefinitionNameFactoryInterface $definitionNameFactory = null,
90
        ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null,
91
    ) {
UNCOV
92
        if (!$definitionNameFactory) {
×
93
            $this->definitionNameFactory = new DefinitionNameFactory();
×
94
        }
UNCOV
95
        $this->resourceMetadataFactory = $resourceMetadataFactory;
×
96

UNCOV
97
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
×
UNCOV
98
            $this->schemaFactory->setSchemaFactory($this);
×
99
        }
100
    }
101

102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function buildSchema(string $className, string $format = 'jsonld', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema
106
    {
NEW
107
        if ('jsonld' !== $format) {
×
UNCOV
108
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
×
109
        }
UNCOV
110
        if (!$this->isResourceClass($className)) {
×
UNCOV
111
            $operation = null;
×
UNCOV
112
            $inputOrOutputClass = null;
×
UNCOV
113
            $serializerContext ??= [];
×
114
        } else {
UNCOV
115
            $operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
×
UNCOV
116
            $inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
×
UNCOV
117
            $serializerContext ??= $this->getSerializerContext($operation, $type);
×
118
        }
119

UNCOV
120
        if (null === $inputOrOutputClass) {
×
121
            // input or output disabled
UNCOV
122
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
×
123
        }
124

125
        // JSON-LD is slightly different then JSON:API or HAL
126
        // All the references that are resources must also be in JSON-LD therefore combining
127
        // the HydraItemBaseSchema and the JSON schema is harder (unless we loop again through all relationship)
128
        // The less intensive path is to compute the jsonld schemas, then to combine in an allOf
UNCOV
129
        $schema = $this->schemaFactory->buildSchema($className, 'jsonld', $type, $operation, $schema, $serializerContext, $forceCollection);
×
UNCOV
130
        $definitions = $schema->getDefinitions();
×
131

UNCOV
132
        $prefix = $this->getSchemaUriPrefix($schema->getVersion());
×
UNCOV
133
        $collectionKey = $schema->getItemsDefinitionKey();
×
134

NEW
135
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
×
NEW
136
        if (Schema::TYPE_INPUT === $type) {
×
NEW
137
            $definitionName .= '.input';
×
138
        }
139

NEW
140
        $jsonSchema = $this->schemaFactory->buildSchema($className, 'json', $type, $operation, new Schema(version: $schema->getVersion()), $serializerContext, $forceCollection);
×
NEW
141
        $jsonKey = $jsonSchema->getRootDefinitionKey() ?? $jsonSchema->getItemsDefinitionKey();
×
NEW
142
        $jsonDefinition = $jsonSchema->getDefinitions()[$jsonKey] ?? null;
×
143

UNCOV
144
        if (!$collectionKey) {
×
NEW
145
            $schema['$ref'] = $prefix.$definitionName;
×
146

UNCOV
147
            if ($this->transformed[$definitionName] ?? false) {
×
UNCOV
148
                return $schema;
×
149
            }
150

NEW
151
            $baseName = Schema::TYPE_OUTPUT === $type ? self::ITEM_BASE_SCHEMA_OUTPUT_NAME : self::ITEM_BASE_SCHEMA_NAME;
×
152

UNCOV
153
            if ($this->isResourceClass($inputOrOutputClass)) {
×
UNCOV
154
                if (!isset($definitions[$baseName])) {
×
UNCOV
155
                    $definitions[$baseName] = Schema::TYPE_OUTPUT === $type ? self::ITEM_BASE_SCHEMA_OUTPUT : self::ITEM_BASE_SCHEMA;
×
156
                }
157
            }
158

NEW
159
            $definitions[$jsonKey] ??= $jsonDefinition;
×
160

UNCOV
161
            $allOf = new \ArrayObject(['allOf' => [
×
UNCOV
162
                ['$ref' => $prefix.$baseName],
×
NEW
163
                ['$ref' => $prefix.$jsonKey],
×
UNCOV
164
            ]]);
×
165

NEW
166
            if (isset($definitions[$jsonKey]['description'])) {
×
NEW
167
                $allOf['description'] = $definitions[$jsonKey]['description'];
×
168
            }
169

UNCOV
170
            $definitions[$definitionName] = $allOf;
×
UNCOV
171
            unset($definitions[$definitionName]['allOf'][1]['description']);
×
172

UNCOV
173
            $this->transformed[$definitionName] = true;
×
174

UNCOV
175
            return $schema;
×
176
        }
177

UNCOV
178
        if (($schema['type'] ?? '') !== 'array') {
×
179
            return $schema;
×
180
        }
181

UNCOV
182
        $hydraPrefix = $this->getHydraPrefix($serializerContext + $this->defaultContext);
×
183

UNCOV
184
        if (!isset($definitions[self::COLLECTION_BASE_SCHEMA_NAME])) {
×
UNCOV
185
            switch ($schema->getVersion()) {
×
186
                // JSON Schema + OpenAPI 3.1
UNCOV
187
                case Schema::VERSION_OPENAPI:
×
UNCOV
188
                case Schema::VERSION_JSON_SCHEMA:
×
UNCOV
189
                    $nullableStringDefinition = ['type' => ['string', 'null']];
×
UNCOV
190
                    break;
×
191
                    // Swagger
192
                default:
193
                    $nullableStringDefinition = ['type' => 'string'];
×
194
                    break;
×
195
            }
196

UNCOV
197
            $definitions[self::COLLECTION_BASE_SCHEMA_NAME] = [
×
UNCOV
198
                'type' => 'object',
×
UNCOV
199
                'required' => [
×
UNCOV
200
                    $hydraPrefix.'member',
×
UNCOV
201
                    'items' => ['type' => 'object'],
×
UNCOV
202
                ],
×
UNCOV
203
                'properties' => [
×
UNCOV
204
                    $hydraPrefix.'member' => [
×
UNCOV
205
                        'type' => 'array',
×
UNCOV
206
                    ],
×
UNCOV
207
                    $hydraPrefix.'totalItems' => [
×
UNCOV
208
                        'type' => 'integer',
×
UNCOV
209
                        'minimum' => 0,
×
UNCOV
210
                    ],
×
UNCOV
211
                    $hydraPrefix.'view' => [
×
UNCOV
212
                        'type' => 'object',
×
UNCOV
213
                        'properties' => [
×
UNCOV
214
                            '@id' => [
×
UNCOV
215
                                'type' => 'string',
×
UNCOV
216
                                'format' => 'iri-reference',
×
UNCOV
217
                            ],
×
UNCOV
218
                            '@type' => [
×
UNCOV
219
                                'type' => 'string',
×
UNCOV
220
                            ],
×
UNCOV
221
                            $hydraPrefix.'first' => [
×
UNCOV
222
                                'type' => 'string',
×
UNCOV
223
                                'format' => 'iri-reference',
×
UNCOV
224
                            ],
×
UNCOV
225
                            $hydraPrefix.'last' => [
×
UNCOV
226
                                'type' => 'string',
×
UNCOV
227
                                'format' => 'iri-reference',
×
UNCOV
228
                            ],
×
UNCOV
229
                            $hydraPrefix.'previous' => [
×
UNCOV
230
                                'type' => 'string',
×
UNCOV
231
                                'format' => 'iri-reference',
×
UNCOV
232
                            ],
×
UNCOV
233
                            $hydraPrefix.'next' => [
×
UNCOV
234
                                'type' => 'string',
×
UNCOV
235
                                'format' => 'iri-reference',
×
UNCOV
236
                            ],
×
UNCOV
237
                        ],
×
UNCOV
238
                        'example' => [
×
UNCOV
239
                            '@id' => 'string',
×
UNCOV
240
                            'type' => 'string',
×
UNCOV
241
                            $hydraPrefix.'first' => 'string',
×
UNCOV
242
                            $hydraPrefix.'last' => 'string',
×
UNCOV
243
                            $hydraPrefix.'previous' => 'string',
×
UNCOV
244
                            $hydraPrefix.'next' => 'string',
×
UNCOV
245
                        ],
×
UNCOV
246
                    ],
×
UNCOV
247
                    $hydraPrefix.'search' => [
×
UNCOV
248
                        'type' => 'object',
×
UNCOV
249
                        'properties' => [
×
UNCOV
250
                            '@type' => ['type' => 'string'],
×
UNCOV
251
                            $hydraPrefix.'template' => ['type' => 'string'],
×
UNCOV
252
                            $hydraPrefix.'variableRepresentation' => ['type' => 'string'],
×
UNCOV
253
                            $hydraPrefix.'mapping' => [
×
UNCOV
254
                                'type' => 'array',
×
UNCOV
255
                                'items' => [
×
UNCOV
256
                                    'type' => 'object',
×
UNCOV
257
                                    'properties' => [
×
UNCOV
258
                                        '@type' => ['type' => 'string'],
×
UNCOV
259
                                        'variable' => ['type' => 'string'],
×
UNCOV
260
                                        'property' => $nullableStringDefinition,
×
UNCOV
261
                                        'required' => ['type' => 'boolean'],
×
UNCOV
262
                                    ],
×
UNCOV
263
                                ],
×
UNCOV
264
                            ],
×
UNCOV
265
                        ],
×
UNCOV
266
                    ],
×
UNCOV
267
                ],
×
UNCOV
268
            ];
×
269
        }
270

UNCOV
271
        $schema['type'] = 'object';
×
UNCOV
272
        $schema['description'] = "$definitionName collection.";
×
UNCOV
273
        $schema['allOf'] = [
×
UNCOV
274
            ['$ref' => $prefix.self::COLLECTION_BASE_SCHEMA_NAME],
×
UNCOV
275
            [
×
UNCOV
276
                'type' => 'object',
×
UNCOV
277
                'properties' => [
×
UNCOV
278
                    $hydraPrefix.'member' => [
×
UNCOV
279
                        'type' => 'array',
×
NEW
280
                        'items' => [
×
NEW
281
                            '$ref' => $prefix.$definitionName,
×
NEW
282
                        ],
×
UNCOV
283
                    ],
×
UNCOV
284
                ],
×
UNCOV
285
            ],
×
UNCOV
286
        ];
×
287

UNCOV
288
        unset($schema['items']);
×
289

UNCOV
290
        return $schema;
×
291
    }
292

293
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
294
    {
UNCOV
295
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
×
UNCOV
296
            $this->schemaFactory->setSchemaFactory($schemaFactory);
×
297
        }
298
    }
299
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc