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

api-platform / core / 18089937549

29 Sep 2025 07:56AM UTC coverage: 21.764% (-0.3%) from 22.093%
18089937549

Pull #7416

github

web-flow
Merge 061bcc790 into abe0438be
Pull Request #7416: fix(laravel): serializer attributes on Eloquent methods

0 of 151 new or added lines in 11 files covered. (0.0%)

5028 existing lines in 173 files now uncovered.

11889 of 54626 relevant lines covered (21.76%)

25.32 hits per line

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

97.14
/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) {
699✔
UNCOV
93
            $this->definitionNameFactory = new DefinitionNameFactory();
×
94
        }
95
        $this->resourceMetadataFactory = $resourceMetadataFactory;
699✔
96

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

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

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

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

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

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

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

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

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

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

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

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

167
            return $schema;
66✔
168
        }
169

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

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

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

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

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

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

279
        return $schema;
36✔
280
    }
281

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