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

api-platform / core / 18283705710

06 Oct 2025 02:10PM UTC coverage: 0.0% (-22.0%) from 21.956%
18283705710

Pull #7397

github

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

0 of 4 new or added lines in 1 file covered. (0.0%)

12313 existing lines in 405 files now uncovered.

0 of 56347 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
    {
107
        // The input schema must not include `@id` or `@type` as required fields, so it should be a pure JSON schema.
108
        // Strictly speaking, it is possible to include `@id` or `@context` in the input,
109
        // but the generated JSON Schema does not include `"additionalProperties": false` by default,
110
        // so it is possible to include `@id` or `@context` in the input even if the input schema is a JSON schema.
NEW
111
        if (Schema::TYPE_INPUT === $type) {
×
NEW
112
            $format = 'json';
×
113
        }
114

NEW
115
        if ('jsonld' !== $format) {
×
UNCOV
116
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
×
117
        }
UNCOV
118
        if (!$this->isResourceClass($className)) {
×
UNCOV
119
            $operation = null;
×
UNCOV
120
            $inputOrOutputClass = null;
×
UNCOV
121
            $serializerContext ??= [];
×
122
        } else {
UNCOV
123
            $operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
×
UNCOV
124
            $inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
×
UNCOV
125
            $serializerContext ??= $this->getSerializerContext($operation, $type);
×
126
        }
127

UNCOV
128
        if (null === $inputOrOutputClass) {
×
129
            // input or output disabled
UNCOV
130
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
×
131
        }
132

UNCOV
133
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
×
134

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

UNCOV
142
        $prefix = $this->getSchemaUriPrefix($schema->getVersion());
×
UNCOV
143
        $collectionKey = $schema->getItemsDefinitionKey();
×
UNCOV
144
        $key = $schema->getRootDefinitionKey() ?? $collectionKey;
×
145

UNCOV
146
        if (!$collectionKey) {
×
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 (!isset($definitions[$baseName])) {
×
UNCOV
154
                $definitions[$baseName] = Schema::TYPE_OUTPUT === $type ? self::ITEM_BASE_SCHEMA_OUTPUT : self::ITEM_BASE_SCHEMA;
×
155
            }
156

UNCOV
157
            $allOf = new \ArrayObject(['allOf' => [
×
UNCOV
158
                ['$ref' => $prefix.$baseName],
×
UNCOV
159
                $definitions[$key],
×
UNCOV
160
            ]]);
×
161

UNCOV
162
            if (isset($definitions[$key]['description'])) {
×
UNCOV
163
                $allOf['description'] = $definitions[$key]['description'];
×
164
            }
165

UNCOV
166
            $definitions[$definitionName] = $allOf;
×
UNCOV
167
            unset($definitions[$definitionName]['allOf'][1]['description']);
×
168

UNCOV
169
            $schema['$ref'] = $prefix.$definitionName;
×
170

UNCOV
171
            $this->transformed[$definitionName] = true;
×
172

UNCOV
173
            return $schema;
×
174
        }
175

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

UNCOV
180
        $hydraPrefix = $this->getHydraPrefix($serializerContext + $this->defaultContext);
×
181

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

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

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

UNCOV
284
        unset($schema['items']);
×
285

UNCOV
286
        return $schema;
×
287
    }
288

289
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
290
    {
UNCOV
291
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
×
UNCOV
292
            $this->schemaFactory->setSchemaFactory($schemaFactory);
×
293
        }
294
    }
295
}
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