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

api-platform / core / 15156535663

21 May 2025 07:47AM UTC coverage: 26.526% (+0.2%) from 26.351%
15156535663

push

github

soyuka
fix(json-schema): share invariable sub-schemas

340 of 485 new or added lines in 23 files covered. (70.1%)

15 existing lines in 7 files now uncovered.

13719 of 51719 relevant lines covered (26.53%)

72.9 hits per line

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

97.86
/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) {
1,816✔
93
            $this->definitionNameFactory = new DefinitionNameFactory();
8✔
94
        }
95
        $this->resourceMetadataFactory = $resourceMetadataFactory;
1,816✔
96

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

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

125
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
97✔
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);
97✔
132
        $definitions = $schema->getDefinitions();
97✔
133

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

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

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

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

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

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

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

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

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

167
            return $schema;
93✔
168
        }
169

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

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

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

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

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

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

279
        return $schema;
63✔
280
    }
281

282
    public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void
283
    {
284
        if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
1,816✔
285
            $this->schemaFactory->setSchemaFactory($schemaFactory);
1,816✔
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