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

api-platform / core / 14954769666

11 May 2025 10:14AM UTC coverage: 0.0% (-8.5%) from 8.457%
14954769666

Pull #7135

github

web-flow
Merge bf21e0bc7 into 4dd0cdfc4
Pull Request #7135: fix(symfony,laravel): InvalidUriVariableException status code (e400)

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

11040 existing lines in 370 files now uncovered.

0 of 48303 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/GraphQl/Type/TypeBuilder.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\GraphQl\Type;
15

16
use ApiPlatform\GraphQl\Serializer\ItemNormalizer;
17
use ApiPlatform\Metadata\ApiProperty;
18
use ApiPlatform\Metadata\CollectionOperationInterface;
19
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
20
use ApiPlatform\Metadata\GraphQl\Mutation;
21
use ApiPlatform\Metadata\GraphQl\Operation;
22
use ApiPlatform\Metadata\GraphQl\Query;
23
use ApiPlatform\Metadata\GraphQl\Subscription;
24
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
25
use ApiPlatform\State\Pagination\Pagination;
26
use GraphQL\Type\Definition\EnumType;
27
use GraphQL\Type\Definition\InputObjectType;
28
use GraphQL\Type\Definition\InterfaceType;
29
use GraphQL\Type\Definition\NonNull;
30
use GraphQL\Type\Definition\ObjectType;
31
use GraphQL\Type\Definition\Type as GraphQLType;
32
use Psr\Container\ContainerInterface;
33
use Symfony\Component\PropertyInfo\Type;
34

35
/**
36
 * Builds the GraphQL types.
37
 *
38
 * @author Alan Poulain <contact@alanpoulain.eu>
39
 */
40
final class TypeBuilder implements ContextAwareTypeBuilderInterface
41
{
42
    private $defaultFieldResolver;
43

44
    public function __construct(private readonly TypesContainerInterface $typesContainer, callable $defaultFieldResolver, private ?ContainerInterface $fieldsBuilderLocator, private readonly Pagination $pagination)
45
    {
UNCOV
46
        $this->fieldsBuilderLocator = $fieldsBuilderLocator;
×
UNCOV
47
        $this->defaultFieldResolver = $defaultFieldResolver;
×
48
    }
49

50
    public function setFieldsBuilderLocator(ContainerInterface $fieldsBuilderLocator): void
51
    {
52
        $this->fieldsBuilderLocator = $fieldsBuilderLocator;
×
53
    }
54

55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function getResourceObjectType(ResourceMetadataCollection $resourceMetadataCollection, Operation $operation, ?ApiProperty $propertyMetadata = null, array $context = []): GraphQLType
59
    {
UNCOV
60
        $shortName = $operation->getShortName();
×
UNCOV
61
        $operationName = $operation->getName();
×
UNCOV
62
        $input = $context['input'];
×
UNCOV
63
        $depth = $context['depth'] ?? 0;
×
UNCOV
64
        $wrapped = $context['wrapped'] ?? false;
×
65

UNCOV
66
        if ($operation instanceof Mutation) {
×
UNCOV
67
            $shortName = $operationName.ucfirst($shortName);
×
68
        }
69

UNCOV
70
        if ($operation instanceof Subscription) {
×
71
            $shortName = $operationName.ucfirst($shortName).'Subscription';
×
72
        }
73

UNCOV
74
        if ($input) {
×
UNCOV
75
            if ($depth > 0) {
×
76
                $shortName .= 'Nested';
×
77
            }
UNCOV
78
            $shortName .= 'Input';
×
UNCOV
79
        } elseif ($operation instanceof Mutation || $operation instanceof Subscription) {
×
UNCOV
80
            if ($depth > 0) {
×
81
                $shortName .= 'Nested';
×
82
            }
UNCOV
83
            $shortName .= 'Payload';
×
84
        }
85

UNCOV
86
        if ('item_query' === $operationName || 'collection_query' === $operationName) {
×
87
            // Test if the collection/item has different groups
UNCOV
88
            if ($resourceMetadataCollection->getOperation($operation instanceof CollectionOperationInterface ? 'item_query' : 'collection_query')->getNormalizationContext() !== $operation->getNormalizationContext()) {
×
89
                $shortName .= $operation instanceof CollectionOperationInterface ? 'Collection' : 'Item';
×
90
            }
91
        }
92

UNCOV
93
        if ($wrapped && ($operation instanceof Mutation || $operation instanceof Subscription)) {
×
94
            $shortName .= 'Data';
×
95
        }
96

UNCOV
97
        $resourceObjectType = null;
×
UNCOV
98
        if (!$this->typesContainer->has($shortName)) {
×
UNCOV
99
            $resourceObjectType = $this->getResourceObjectTypeConfiguration($shortName, $resourceMetadataCollection, $operation, $context);
×
UNCOV
100
            $this->typesContainer->set($shortName, $resourceObjectType);
×
101
        }
102

UNCOV
103
        $resourceObjectType = $resourceObjectType ?? $this->typesContainer->get($shortName);
×
UNCOV
104
        if (!($resourceObjectType instanceof ObjectType || $resourceObjectType instanceof NonNull || $resourceObjectType instanceof InputObjectType)) {
×
105
            throw new \LogicException(\sprintf('Expected GraphQL type "%s" to be %s.', $shortName, implode('|', [ObjectType::class, NonNull::class, InputObjectType::class])));
×
106
        }
107

UNCOV
108
        $required = $propertyMetadata?->isRequired() ?? true;
×
UNCOV
109
        if ($required && $input) {
×
UNCOV
110
            $resourceObjectType = GraphQLType::nonNull($resourceObjectType);
×
111
        }
112

UNCOV
113
        return $resourceObjectType;
×
114
    }
115

116
    /**
117
     * {@inheritdoc}
118
     */
119
    public function getNodeInterface(): InterfaceType
120
    {
UNCOV
121
        if ($this->typesContainer->has('Node')) {
×
UNCOV
122
            $nodeInterface = $this->typesContainer->get('Node');
×
UNCOV
123
            if (!$nodeInterface instanceof InterfaceType) {
×
124
                throw new \LogicException(\sprintf('Expected GraphQL type "Node" to be %s.', InterfaceType::class));
×
125
            }
126

UNCOV
127
            return $nodeInterface;
×
128
        }
129

UNCOV
130
        $nodeInterface = new InterfaceType([
×
UNCOV
131
            'name' => 'Node',
×
UNCOV
132
            'description' => 'A node, according to the Relay specification.',
×
UNCOV
133
            'fields' => [
×
UNCOV
134
                'id' => [
×
UNCOV
135
                    'type' => GraphQLType::nonNull(GraphQLType::id()),
×
UNCOV
136
                    'description' => 'The id of this node.',
×
UNCOV
137
                ],
×
UNCOV
138
            ],
×
UNCOV
139
            'resolveType' => function ($value): ?GraphQLType {
×
140
                if (!isset($value[ItemNormalizer::ITEM_RESOURCE_CLASS_KEY])) {
×
141
                    return null;
×
142
                }
143

144
                $shortName = (new \ReflectionClass($value[ItemNormalizer::ITEM_RESOURCE_CLASS_KEY]))->getShortName();
×
145

146
                return $this->typesContainer->has($shortName) ? $this->typesContainer->get($shortName) : null;
×
UNCOV
147
            },
×
UNCOV
148
        ]);
×
149

UNCOV
150
        $this->typesContainer->set('Node', $nodeInterface);
×
151

UNCOV
152
        return $nodeInterface;
×
153
    }
154

155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function getResourcePaginatedCollectionType(GraphQLType $resourceType, string $resourceClass, Operation $operation): GraphQLType
159
    {
160
        @trigger_error('Using getResourcePaginatedCollectionType method of TypeBuilder is deprecated since API Platform 3.1. Use getPaginatedCollectionType method instead.', \E_USER_DEPRECATED);
×
161

162
        return $this->getPaginatedCollectionType($resourceType, $operation);
×
163
    }
164

165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function getPaginatedCollectionType(GraphQLType $resourceType, Operation $operation): GraphQLType
169
    {
UNCOV
170
        $namedType = GraphQLType::getNamedType($resourceType);
×
171
        // graphql-php 15: name() exists
UNCOV
172
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
×
UNCOV
173
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
×
174

UNCOV
175
        $connectionTypeKey = \sprintf('%s%sConnection', $shortName, ucfirst($paginationType));
×
UNCOV
176
        if ($this->typesContainer->has($connectionTypeKey)) {
×
UNCOV
177
            return $this->typesContainer->get($connectionTypeKey);
×
178
        }
179

UNCOV
180
        $fields = 'cursor' === $paginationType ?
×
UNCOV
181
            $this->getCursorBasedPaginationFields($resourceType) :
×
182
            $this->getPageBasedPaginationFields($resourceType);
×
183

UNCOV
184
        $configuration = [
×
UNCOV
185
            'name' => $connectionTypeKey,
×
UNCOV
186
            'description' => \sprintf("%s connection for $shortName.", ucfirst($paginationType)),
×
UNCOV
187
            'fields' => $fields,
×
UNCOV
188
        ];
×
189

UNCOV
190
        $resourcePaginatedCollectionType = new ObjectType($configuration);
×
UNCOV
191
        $this->typesContainer->set($connectionTypeKey, $resourcePaginatedCollectionType);
×
192

UNCOV
193
        return $resourcePaginatedCollectionType;
×
194
    }
195

196
    public function getEnumType(Operation $operation): GraphQLType
197
    {
UNCOV
198
        $enumName = $operation->getShortName();
×
199

UNCOV
200
        if ($this->typesContainer->has($enumName)) {
×
201
            return $this->typesContainer->get($enumName);
×
202
        }
203

204
        /** @var FieldsBuilderEnumInterface $fieldsBuilder */
UNCOV
205
        $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
×
UNCOV
206
        $enumCases = [];
×
UNCOV
207
        $enumCases = $fieldsBuilder->getEnumFields($operation->getClass());
×
208

UNCOV
209
        $enumConfig = [
×
UNCOV
210
            'name' => $enumName,
×
UNCOV
211
            'values' => $enumCases,
×
UNCOV
212
        ];
×
UNCOV
213
        if ($enumDescription = $operation->getDescription()) {
×
214
            $enumConfig['description'] = $enumDescription;
×
215
        }
216

UNCOV
217
        $enumType = new EnumType($enumConfig);
×
UNCOV
218
        $this->typesContainer->set($enumName, $enumType);
×
219

UNCOV
220
        return $enumType;
×
221
    }
222

223
    /**
224
     * {@inheritdoc}
225
     */
226
    public function isCollection(Type $type): bool
227
    {
UNCOV
228
        return $type->isCollection() && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null) && null !== $collectionValueType->getClassName();
×
229
    }
230

231
    private function getCursorBasedPaginationFields(GraphQLType $resourceType): array
232
    {
UNCOV
233
        $namedType = GraphQLType::getNamedType($resourceType);
×
234
        // graphql-php 15: name() exists
UNCOV
235
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
×
236

UNCOV
237
        $edgeObjectTypeConfiguration = [
×
UNCOV
238
            'name' => "{$shortName}Edge",
×
UNCOV
239
            'description' => "Edge of $shortName.",
×
UNCOV
240
            'fields' => [
×
UNCOV
241
                'node' => $resourceType,
×
UNCOV
242
                'cursor' => GraphQLType::nonNull(GraphQLType::string()),
×
UNCOV
243
            ],
×
UNCOV
244
        ];
×
UNCOV
245
        $edgeObjectType = new ObjectType($edgeObjectTypeConfiguration);
×
UNCOV
246
        $this->typesContainer->set("{$shortName}Edge", $edgeObjectType);
×
247

UNCOV
248
        $pageInfoObjectTypeConfiguration = [
×
UNCOV
249
            'name' => "{$shortName}PageInfo",
×
UNCOV
250
            'description' => 'Information about the current page.',
×
UNCOV
251
            'fields' => [
×
UNCOV
252
                'endCursor' => GraphQLType::string(),
×
UNCOV
253
                'startCursor' => GraphQLType::string(),
×
UNCOV
254
                'hasNextPage' => GraphQLType::nonNull(GraphQLType::boolean()),
×
UNCOV
255
                'hasPreviousPage' => GraphQLType::nonNull(GraphQLType::boolean()),
×
UNCOV
256
            ],
×
UNCOV
257
        ];
×
UNCOV
258
        $pageInfoObjectType = new ObjectType($pageInfoObjectTypeConfiguration);
×
UNCOV
259
        $this->typesContainer->set("{$shortName}PageInfo", $pageInfoObjectType);
×
260

UNCOV
261
        return [
×
UNCOV
262
            'edges' => GraphQLType::listOf($edgeObjectType),
×
UNCOV
263
            'pageInfo' => GraphQLType::nonNull($pageInfoObjectType),
×
UNCOV
264
            'totalCount' => GraphQLType::nonNull(GraphQLType::int()),
×
UNCOV
265
        ];
×
266
    }
267

268
    private function getPageBasedPaginationFields(GraphQLType $resourceType): array
269
    {
270
        $namedType = GraphQLType::getNamedType($resourceType);
×
271
        // graphql-php 15: name() exists
272
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
×
273

274
        $paginationInfoObjectTypeConfiguration = [
×
275
            'name' => "{$shortName}PaginationInfo",
×
276
            'description' => 'Information about the pagination.',
×
277
            'fields' => [
×
278
                'itemsPerPage' => GraphQLType::nonNull(GraphQLType::int()),
×
279
                'lastPage' => GraphQLType::nonNull(GraphQLType::int()),
×
280
                'totalCount' => GraphQLType::nonNull(GraphQLType::int()),
×
281
                'currentPage' => GraphQLType::nonNull(GraphQLType::int()),
×
282
                'hasNextPage' => GraphQLType::nonNull(GraphQLType::boolean()),
×
283
            ],
×
284
        ];
×
285
        $paginationInfoObjectType = new ObjectType($paginationInfoObjectTypeConfiguration);
×
286
        $this->typesContainer->set("{$shortName}PaginationInfo", $paginationInfoObjectType);
×
287

288
        return [
×
289
            'collection' => GraphQLType::listOf($resourceType),
×
290
            'paginationInfo' => GraphQLType::nonNull($paginationInfoObjectType),
×
291
        ];
×
292
    }
293

294
    private function getQueryOperation(ResourceMetadataCollection $resourceMetadataCollection): ?Operation
295
    {
UNCOV
296
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
UNCOV
297
            foreach ($resourceMetadata->getGraphQlOperations() as $operation) {
×
298
                // Filter the custom queries.
UNCOV
299
                if ($operation instanceof Query && !$operation->getResolver()) {
×
UNCOV
300
                    return $operation;
×
301
                }
302
            }
303
        }
304

305
        return null;
×
306
    }
307

308
    private function getResourceObjectTypeConfiguration(string $shortName, ResourceMetadataCollection $resourceMetadataCollection, Operation $operation, array $context = []): InputObjectType|ObjectType
309
    {
UNCOV
310
        $operationName = $operation->getName();
×
UNCOV
311
        $resourceClass = $operation->getClass();
×
UNCOV
312
        $input = $context['input'];
×
UNCOV
313
        $depth = $context['depth'] ?? 0;
×
UNCOV
314
        $wrapped = $context['wrapped'] ?? false;
×
315

UNCOV
316
        $ioMetadata = $input ? $operation->getInput() : $operation->getOutput();
×
UNCOV
317
        if (null !== $ioMetadata && \array_key_exists('class', $ioMetadata) && null !== $ioMetadata['class']) {
×
318
            $resourceClass = $ioMetadata['class'];
×
319
        }
320

UNCOV
321
        $wrapData = !$wrapped && ($operation instanceof Mutation || $operation instanceof Subscription) && !$input && $depth < 1;
×
322

UNCOV
323
        $configuration = [
×
UNCOV
324
            'name' => $shortName,
×
UNCOV
325
            'description' => $operation->getDescription(),
×
UNCOV
326
            'resolveField' => $this->defaultFieldResolver,
×
UNCOV
327
            'fields' => function () use ($resourceClass, $operation, $operationName, $resourceMetadataCollection, $input, $wrapData, $depth, $ioMetadata) {
×
UNCOV
328
                if ($wrapData) {
×
UNCOV
329
                    $queryNormalizationContext = $this->getQueryOperation($resourceMetadataCollection)?->getNormalizationContext() ?? [];
×
330

331
                    try {
UNCOV
332
                        $mutationNormalizationContext = $operation instanceof Mutation || $operation instanceof Subscription ? ($resourceMetadataCollection->getOperation($operationName)->getNormalizationContext() ?? []) : [];
×
333
                    } catch (OperationNotFoundException) {
×
334
                        $mutationNormalizationContext = [];
×
335
                    }
336
                    // Use a new type for the wrapped object only if there is a specific normalization context for the mutation or the subscription.
337
                    // If not, use the query type in order to ensure the client cache could be used.
UNCOV
338
                    $useWrappedType = $queryNormalizationContext !== $mutationNormalizationContext;
×
339

UNCOV
340
                    $wrappedOperationName = $operationName;
×
341

UNCOV
342
                    if (!$useWrappedType) {
×
UNCOV
343
                        $wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
×
344
                    }
345

UNCOV
346
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
×
347

UNCOV
348
                    $fields = [
×
UNCOV
349
                        lcfirst($wrappedOperation->getShortName()) => $this->getResourceObjectType($resourceMetadataCollection, $wrappedOperation instanceof Operation ? $wrappedOperation : null, null, [
×
UNCOV
350
                            'input' => $input,
×
UNCOV
351
                            'wrapped' => true,
×
UNCOV
352
                            'depth' => $depth,
×
UNCOV
353
                        ]),
×
UNCOV
354
                    ];
×
355

UNCOV
356
                    if ($operation instanceof Subscription) {
×
357
                        $fields['clientSubscriptionId'] = GraphQLType::string();
×
358
                        if ($operation->getMercure()) {
×
359
                            $fields['mercureUrl'] = GraphQLType::string();
×
360
                        }
361

362
                        return $fields;
×
363
                    }
364

UNCOV
365
                    return $fields + ['clientMutationId' => GraphQLType::string()];
×
366
                }
367

UNCOV
368
                $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
×
UNCOV
369
                $fields = $fieldsBuilder->getResourceObjectTypeFields($resourceClass, $operation, $input, $depth, $ioMetadata);
×
370

UNCOV
371
                if ($input && $operation instanceof Mutation && null !== $mutationArgs = $operation->getArgs()) {
×
372
                    return $fieldsBuilder->resolveResourceArgs($mutationArgs, $operation) + ['clientMutationId' => $fields['clientMutationId']];
×
373
                }
UNCOV
374
                if ($input && $operation instanceof Mutation && null !== $extraMutationArgs = $operation->getExtraArgs()) {
×
375
                    return $fields + $fieldsBuilder->resolveResourceArgs($extraMutationArgs, $operation);
×
376
                }
377

UNCOV
378
                return $fields;
×
UNCOV
379
            },
×
UNCOV
380
            'interfaces' => $wrapData ? [] : [$this->getNodeInterface()],
×
UNCOV
381
        ];
×
382

UNCOV
383
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
×
384
    }
385
}
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