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

api-platform / core / 18308695687

07 Oct 2025 09:45AM UTC coverage: 24.55% (+0.02%) from 24.533%
18308695687

push

github

web-flow
fix(hydra): genId false schema (#7440)

15 of 24 new or added lines in 3 files covered. (62.5%)

4 existing lines in 1 file now uncovered.

13992 of 56994 relevant lines covered (24.55%)

25.85 hits per line

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

97.24
/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_WITHOUT_ID_BASE_SCHEMA_NAME = 'HydraItemBaseSchemaWithoutId';
41
    private const COLLECTION_BASE_SCHEMA_NAME = 'HydraCollectionBaseSchema';
42

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

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

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

83
    /**
84
     * @var array<string, true>
85
     */
86
    private array $transformed = [];
87

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

102
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
739✔
103
            $this->schemaFactory->setSchemaFactory($this);
739✔
104
        }
105
    }
106

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

120
        if ('jsonld' !== $format) {
152✔
121
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
100✔
122
        }
123
        if (!$this->isResourceClass($className)) {
100✔
124
            $operation = null;
54✔
125
            $inputOrOutputClass = null;
54✔
126
            $serializerContext ??= [];
54✔
127
        } else {
128
            $operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
100✔
129
            $inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
100✔
130
            $serializerContext ??= $this->getSerializerContext($operation, $type);
100✔
131
        }
132

133
        if (null === $inputOrOutputClass) {
100✔
134
            // input or output disabled
135
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
54✔
136
        }
137

138
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
100✔
139

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

147
        $prefix = $this->getSchemaUriPrefix($schema->getVersion());
100✔
148
        $collectionKey = $schema->getItemsDefinitionKey();
100✔
149
        $key = $schema->getRootDefinitionKey() ?? $collectionKey;
100✔
150

151
        if (!$collectionKey) {
100✔
152
            if ($this->transformed[$definitionName] ?? false) {
96✔
153
                return $schema;
46✔
154
            }
155

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

159
            if ($hasNoId) {
96✔
160
                $baseName = self::ITEM_WITHOUT_ID_BASE_SCHEMA_NAME;
2✔
161
            }
162

163
            if (!isset($definitions[$baseName])) {
96✔
164
                $definitions[$baseName] = $hasNoId ? self::ITEM_BASE_SCHEMA_WITHOUT_ID : self::ITEM_BASE_SCHEMA_WITH_ID;
96✔
165
            }
166

167
            $allOf = new \ArrayObject(['allOf' => [
96✔
168
                ['$ref' => $prefix.$baseName],
96✔
169
                $definitions[$key],
96✔
170
            ]]);
96✔
171

172
            if (isset($definitions[$key]['description'])) {
96✔
173
                $allOf['description'] = $definitions[$key]['description'];
56✔
174
            }
175

176
            $definitions[$definitionName] = $allOf;
96✔
177
            unset($definitions[$definitionName]['allOf'][1]['description']);
96✔
178

179
            $schema['$ref'] = $prefix.$definitionName;
96✔
180

181
            $this->transformed[$definitionName] = true;
96✔
182

183
            return $schema;
96✔
184
        }
185

186
        if (($schema['type'] ?? '') !== 'array') {
64✔
UNCOV
187
            return $schema;
×
188
        }
189

190
        $hydraPrefix = $this->getHydraPrefix($serializerContext + $this->defaultContext);
64✔
191

192
        if (!isset($definitions[self::COLLECTION_BASE_SCHEMA_NAME])) {
64✔
193
            switch ($schema->getVersion()) {
64✔
194
                // JSON Schema + OpenAPI 3.1
195
                case Schema::VERSION_OPENAPI:
64✔
196
                case Schema::VERSION_JSON_SCHEMA:
16✔
197
                    $nullableStringDefinition = ['type' => ['string', 'null']];
64✔
198
                    break;
64✔
199
                    // Swagger
200
                default:
UNCOV
201
                    $nullableStringDefinition = ['type' => 'string'];
×
UNCOV
202
                    break;
×
203
            }
204

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

279
        $schema['type'] = 'object';
64✔
280
        $schema['description'] = "$definitionName collection.";
64✔
281
        $schema['allOf'] = [
64✔
282
            ['$ref' => $prefix.self::COLLECTION_BASE_SCHEMA_NAME],
64✔
283
            [
64✔
284
                'type' => 'object',
64✔
285
                'properties' => [
64✔
286
                    $hydraPrefix.'member' => [
64✔
287
                        'type' => 'array',
64✔
288
                        'items' => $schema['items'],
64✔
289
                    ],
64✔
290
                ],
64✔
291
            ],
64✔
292
        ];
64✔
293

294
        unset($schema['items']);
64✔
295

296
        return $schema;
64✔
297
    }
298

299
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
300
    {
301
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
739✔
302
            $this->schemaFactory->setSchemaFactory($schemaFactory);
739✔
303
        }
304
    }
305
}
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