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

api-platform / core / 15255731762

26 May 2025 01:55PM UTC coverage: 0.0% (-26.5%) from 26.526%
15255731762

Pull #7176

github

web-flow
Merge 66f6cf4d2 into 79edced67
Pull Request #7176: Merge 4.1

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

11394 existing lines in 372 files now uncovered.

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/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 as LegacyType;
34
use Symfony\Component\TypeInfo\Type;
35

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
114
        return $resourceObjectType;
×
115
    }
116

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

UNCOV
128
            return $nodeInterface;
×
129
        }
130

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

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

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

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

UNCOV
153
        return $nodeInterface;
×
154
    }
155

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

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

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

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

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

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

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

UNCOV
194
        return $resourcePaginatedCollectionType;
×
195
    }
196

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

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

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

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

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

UNCOV
221
        return $enumType;
×
222
    }
223

224
    /**
225
     * {@inheritdoc}
226
     */
227
    public function isCollection(LegacyType $type): bool
228
    {
229
        trigger_deprecation('api-platform/graphql', '4.2', 'The "%s()" method is deprecated and will be removed.', __METHOD__, self::class);
×
230

231
        return $type->isCollection() && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null) && null !== $collectionValueType->getClassName();
×
232
    }
233

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

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

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

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

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

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

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

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

308
        return null;
×
309
    }
310

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

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

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

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

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

UNCOV
343
                    $wrappedOperationName = $operationName;
×
344

UNCOV
345
                    if (!$useWrappedType) {
×
UNCOV
346
                        $wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
×
347
                    }
348

UNCOV
349
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
×
350

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

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

365
                        return $fields;
×
366
                    }
367

UNCOV
368
                    return $fields + ['clientMutationId' => GraphQLType::string()];
×
369
                }
370

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

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

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

UNCOV
386
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
×
387
    }
388
}
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