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

api-platform / core / 15283185369

27 May 2025 06:43PM UTC coverage: 0.0% (-26.4%) from 26.397%
15283185369

Pull #7180

github

web-flow
Merge 9a6703d44 into c022b441b
Pull Request #7180: feat(deps): allow Elasticsearch v9

0 of 51334 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
    ) {
92
        if (!$definitionNameFactory) {
×
93
            $this->definitionNameFactory = new DefinitionNameFactory();
×
94
        }
95
        $this->resourceMetadataFactory = $resourceMetadataFactory;
×
96

97
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
×
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
        if ('jsonld' !== $format || 'input' === $type) {
×
108
            return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
×
109
        }
110
        if (!$this->isResourceClass($className)) {
×
111
            $operation = null;
×
112
            $inputOrOutputClass = null;
×
113
            $serializerContext ??= [];
×
114
        } else {
115
            $operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
×
116
            $inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
×
117
            $serializerContext ??= $this->getSerializerContext($operation, $type);
×
118
        }
119

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

125
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
×
126

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

134
        $prefix = $this->getSchemaUriPrefix($schema->getVersion());
×
135
        $collectionKey = $schema->getItemsDefinitionKey();
×
136
        $key = $schema->getRootDefinitionKey() ?? $collectionKey;
×
137

138
        if (!$collectionKey) {
×
139
            if ($this->transformed[$definitionName] ?? false) {
×
140
                return $schema;
×
141
            }
142

143
            $baseName = Schema::TYPE_OUTPUT === $type ? self::ITEM_BASE_SCHEMA_NAME : self::ITEM_BASE_SCHEMA_OUTPUT_NAME;
×
144

145
            if ($this->isResourceClass($inputOrOutputClass)) {
×
146
                if (!isset($definitions[$baseName])) {
×
147
                    $definitions[$baseName] = Schema::TYPE_OUTPUT === $type ? self::ITEM_BASE_SCHEMA_OUTPUT : self::ITEM_BASE_SCHEMA;
×
148
                }
149
            }
150

151
            $allOf = new \ArrayObject(['allOf' => [
×
152
                ['$ref' => $prefix.$baseName],
×
153
                $definitions[$key],
×
154
            ]]);
×
155

156
            if (isset($definitions[$key]['description'])) {
×
157
                $allOf['description'] = $definitions[$key]['description'];
×
158
            }
159

160
            $definitions[$definitionName] = $allOf;
×
161
            unset($definitions[$definitionName]['allOf'][1]['description']);
×
162

163
            $schema['$ref'] = $prefix.$definitionName;
×
164

165
            $this->transformed[$definitionName] = true;
×
166

167
            return $schema;
×
168
        }
169

170
        if (($schema['type'] ?? '') !== 'array') {
×
171
            return $schema;
×
172
        }
173

174
        $hydraPrefix = $this->getHydraPrefix($serializerContext + $this->defaultContext);
×
175

176
        if (!isset($definitions[self::COLLECTION_BASE_SCHEMA_NAME])) {
×
177
            switch ($schema->getVersion()) {
×
178
                // JSON Schema + OpenAPI 3.1
179
                case Schema::VERSION_OPENAPI:
×
180
                case Schema::VERSION_JSON_SCHEMA:
×
181
                    $nullableStringDefinition = ['type' => ['string', 'null']];
×
182
                    break;
×
183
                    // Swagger
184
                default:
185
                    $nullableStringDefinition = ['type' => 'string'];
×
186
                    break;
×
187
            }
188

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

262
        $schema['type'] = 'object';
×
263
        $schema['description'] = "$definitionName collection.";
×
264
        $schema['allOf'] = [
×
265
            ['$ref' => $prefix.self::COLLECTION_BASE_SCHEMA_NAME],
×
266
            [
×
267
                'type' => 'object',
×
268
                'properties' => [
×
269
                    $hydraPrefix.'member' => [
×
270
                        'type' => 'array',
×
271
                        'items' => $schema['items'],
×
272
                    ],
×
273
                ],
×
274
            ],
×
275
        ];
×
276

277
        unset($schema['items']);
×
278

279
        return $schema;
×
280
    }
281

282
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
283
    {
284
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
×
285
            $this->schemaFactory->setSchemaFactory($schemaFactory);
×
286
        }
287
    }
288
}
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