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

api-platform / core / 18370496742

09 Oct 2025 08:35AM UTC coverage: 0.0% (-21.9%) from 21.92%
18370496742

push

github

soyuka
docs: changelog 4.2.2

0 of 56436 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_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) {
×
98
            $this->definitionNameFactory = new DefinitionNameFactory();
×
99
        }
100
        $this->resourceMetadataFactory = $resourceMetadataFactory;
×
101

102
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
×
103
            $this->schemaFactory->setSchemaFactory($this);
×
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) {
×
117
            $format = 'json';
×
118
        }
119

120
        if ('jsonld' !== $format || !$this->isResourceClass($className)) {
×
121
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
×
122
        }
123

124
        $operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
×
125
        $inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
×
126
        $serializerContext ??= $this->getSerializerContext($operation, $type);
×
127

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

133
        $schema = $this->schemaFactory->buildSchema($className, 'jsonld', $type, $operation, $schema, $serializerContext, $forceCollection);
×
134
        $definitions = $schema->getDefinitions();
×
135
        $prefix = $this->getSchemaUriPrefix($schema->getVersion());
×
136
        $collectionKey = $schema->getItemsDefinitionKey();
×
137

138
        if (!$collectionKey) {
×
139
            $definitionName = $schema->getRootDefinitionKey() ?? $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
×
140
            $this->decorateItemDefinition($definitionName, $definitions, $prefix, $type, $serializerContext);
×
141

142
            if (isset($definitions[$definitionName])) {
×
143
                $currentDefinitions = $schema->getDefinitions();
×
144
                $schema->exchangeArray([]); // Clear the schema
×
145
                $schema['$ref'] = $prefix.$definitionName;
×
146
                $schema->setDefinitions($currentDefinitions);
×
147
            }
148

149
            return $schema;
×
150
        }
151

152
        if (($schema['type'] ?? '') !== 'array') {
×
153
            return $schema;
×
154
        }
155

156
        $hydraPrefix = $this->getHydraPrefix($serializerContext + $this->defaultContext);
×
157

158
        if (!isset($definitions[self::COLLECTION_BASE_SCHEMA_NAME])) {
×
159
            switch ($schema->getVersion()) {
×
160
                // JSON Schema + OpenAPI 3.1
161
                case Schema::VERSION_OPENAPI:
×
162
                case Schema::VERSION_JSON_SCHEMA:
×
163
                    $nullableStringDefinition = ['type' => ['string', 'null']];
×
164
                    break;
×
165
                    // Swagger
166
                default:
167
                    $nullableStringDefinition = ['type' => 'string'];
×
168
                    break;
×
169
            }
170

171
            $definitions[self::COLLECTION_BASE_SCHEMA_NAME] = [
×
172
                'type' => 'object',
×
173
                'required' => [
×
174
                    $hydraPrefix.'member',
×
175
                ],
×
176
                'properties' => [
×
177
                    $hydraPrefix.'member' => [
×
178
                        'type' => 'array',
×
179
                        'items' => ['type' => 'object'],
×
180
                    ],
×
181
                    $hydraPrefix.'totalItems' => [
×
182
                        'type' => 'integer',
×
183
                        'minimum' => 0,
×
184
                    ],
×
185
                    $hydraPrefix.'view' => [
×
186
                        'type' => 'object',
×
187
                        'properties' => [
×
188
                            '@id' => [
×
189
                                'type' => 'string',
×
190
                                'format' => 'iri-reference',
×
191
                            ],
×
192
                            '@type' => [
×
193
                                'type' => 'string',
×
194
                            ],
×
195
                            $hydraPrefix.'first' => [
×
196
                                'type' => 'string',
×
197
                                'format' => 'iri-reference',
×
198
                            ],
×
199
                            $hydraPrefix.'last' => [
×
200
                                'type' => 'string',
×
201
                                'format' => 'iri-reference',
×
202
                            ],
×
203
                            $hydraPrefix.'previous' => [
×
204
                                'type' => 'string',
×
205
                                'format' => 'iri-reference',
×
206
                            ],
×
207
                            $hydraPrefix.'next' => [
×
208
                                'type' => 'string',
×
209
                                'format' => 'iri-reference',
×
210
                            ],
×
211
                        ],
×
212
                        'example' => [
×
213
                            '@id' => 'string',
×
214
                            'type' => 'string',
×
215
                            $hydraPrefix.'first' => 'string',
×
216
                            $hydraPrefix.'last' => 'string',
×
217
                            $hydraPrefix.'previous' => 'string',
×
218
                            $hydraPrefix.'next' => 'string',
×
219
                        ],
×
220
                    ],
×
221
                    $hydraPrefix.'search' => [
×
222
                        'type' => 'object',
×
223
                        'properties' => [
×
224
                            '@type' => ['type' => 'string'],
×
225
                            $hydraPrefix.'template' => ['type' => 'string'],
×
226
                            $hydraPrefix.'variableRepresentation' => ['type' => 'string'],
×
227
                            $hydraPrefix.'mapping' => [
×
228
                                'type' => 'array',
×
229
                                'items' => [
×
230
                                    'type' => 'object',
×
231
                                    'properties' => [
×
232
                                        '@type' => ['type' => 'string'],
×
233
                                        'variable' => ['type' => 'string'],
×
234
                                        'property' => $nullableStringDefinition,
×
235
                                        'required' => ['type' => 'boolean'],
×
236
                                    ],
×
237
                                ],
×
238
                            ],
×
239
                        ],
×
240
                    ],
×
241
                ],
×
242
            ];
×
243
        }
244

245
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
×
246
        $schema['type'] = 'object';
×
247
        $schema['description'] = "$definitionName collection.";
×
248
        $schema['allOf'] = [
×
249
            ['$ref' => $prefix.self::COLLECTION_BASE_SCHEMA_NAME],
×
250
            [
×
251
                'type' => 'object',
×
252
                'properties' => [
×
253
                    $hydraPrefix.'member' => [
×
254
                        'type' => 'array',
×
255
                        'items' => $schema['items'],
×
256
                    ],
×
257
                ],
×
258
            ],
×
259
        ];
×
260

261
        unset($schema['items']);
×
262

263
        if (isset($definitions[$collectionKey])) {
×
264
            $this->decorateItemDefinition($collectionKey, $definitions, $prefix, $type, $serializerContext);
×
265
        }
266

267
        return $schema;
×
268
    }
269

270
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
271
    {
272
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
×
273
            $this->schemaFactory->setSchemaFactory($schemaFactory);
×
274
        }
275
    }
276

277
    private function decorateItemDefinition(string $definitionName, \ArrayObject $definitions, string $prefix, string $type, ?array $serializerContext): void
278
    {
279
        if (!isset($definitions[$definitionName]) || ($this->transformed[$definitionName] ?? false)) {
×
280
            return;
×
281
        }
282

283
        $hasNoId = Schema::TYPE_OUTPUT === $type && false === ($serializerContext['gen_id'] ?? true);
×
284
        $baseName = self::ITEM_BASE_SCHEMA_NAME;
×
285
        if ($hasNoId) {
×
286
            $baseName = self::ITEM_WITHOUT_ID_BASE_SCHEMA_NAME;
×
287
        }
288

289
        if (!isset($definitions[$baseName])) {
×
290
            $definitions[$baseName] = $hasNoId ? self::ITEM_BASE_SCHEMA_WITHOUT_ID : self::ITEM_BASE_SCHEMA_WITH_ID;
×
291
        }
292

293
        $allOf = new \ArrayObject(['allOf' => [
×
294
            ['$ref' => $prefix.$baseName],
×
295
            $definitions[$definitionName],
×
296
        ]]);
×
297

298
        if (isset($definitions[$definitionName]['description'])) {
×
299
            $allOf['description'] = $definitions[$definitionName]['description'];
×
300
        }
301

302
        $definitions[$definitionName] = $allOf;
×
303
        unset($definitions[$definitionName]['allOf'][1]['description']);
×
304

305
        $this->transformed[$definitionName] = true;
×
306
    }
307
}
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