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

api-platform / core / 15069419398

16 May 2025 01:19PM UTC coverage: 21.832%. First build
15069419398

Pull #6960

github

web-flow
Merge 88ff9fb4b into b6080d419
Pull Request #6960: feat(json-schema): mutualize json schema between formats

0 of 470 new or added lines in 25 files covered. (0.0%)

11116 of 50915 relevant lines covered (21.83%)

29.49 hits per line

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

96.43
/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
    ) {
NEW
92
        if (!$definitionNameFactory) {
710✔
NEW
93
            $this->definitionNameFactory = new DefinitionNameFactory();
×
94
        }
NEW
95
        $this->resourceMetadataFactory = $resourceMetadataFactory;
710✔
96

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

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

NEW
125
        $definitionName = $this->definitionNameFactory->create($className, $format, $inputOrOutputClass, $operation, $serializerContext);
15✔
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
NEW
131
        $schema = $this->schemaFactory->buildSchema($className, 'jsonld', $type, $operation, $schema, $serializerContext, $forceCollection);
15✔
132
        $definitions = $schema->getDefinitions();
15✔
133

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

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

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

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

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

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

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

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

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

167
            return $schema;
15✔
168
        }
169

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

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

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

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

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

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

279
        return $schema;
15✔
280
    }
281

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

© 2025 Coveralls, Inc