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

api-platform / core / 15276908793

27 May 2025 01:41PM UTC coverage: 26.397% (+4.7%) from 21.714%
15276908793

push

github

web-flow
chore: type-info v7.3.0-RC1 #7177 (#7178)

13727 of 52003 relevant lines covered (26.4%)

72.72 hits per line

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

93.88
/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
    {
47
        $this->fieldsBuilderLocator = $fieldsBuilderLocator;
308✔
48
        $this->defaultFieldResolver = $defaultFieldResolver;
308✔
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
    {
61
        $shortName = $operation->getShortName();
304✔
62
        $operationName = $operation->getName();
304✔
63
        $input = $context['input'];
304✔
64
        $depth = $context['depth'] ?? 0;
304✔
65
        $wrapped = $context['wrapped'] ?? false;
304✔
66

67
        if ($operation instanceof Mutation) {
304✔
68
            $shortName = $operationName.ucfirst($shortName);
288✔
69
        }
70

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

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

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

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

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

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

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

114
        return $resourceObjectType;
304✔
115
    }
116

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

128
            return $nodeInterface;
304✔
129
        }
130

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

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

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

151
        $this->typesContainer->set('Node', $nodeInterface);
304✔
152

153
        return $nodeInterface;
304✔
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
    {
171
        $namedType = GraphQLType::getNamedType($resourceType);
290✔
172
        // graphql-php 15: name() exists
173
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
290✔
174
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
290✔
175

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

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

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

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

194
        return $resourcePaginatedCollectionType;
290✔
195
    }
196

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

201
        if ($this->typesContainer->has($enumName)) {
11✔
202
            return $this->typesContainer->get($enumName);
7✔
203
        }
204

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

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

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

221
        return $enumType;
11✔
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
    {
236
        $namedType = GraphQLType::getNamedType($resourceType);
290✔
237
        // graphql-php 15: name() exists
238
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
290✔
239

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

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

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

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

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

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

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

308
        return null;
×
309
    }
310

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

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

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

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

334
                    try {
335
                        $mutationNormalizationContext = $operation instanceof Mutation || $operation instanceof Subscription ? ($resourceMetadataCollection->getOperation($operationName)->getNormalizationContext() ?? []) : [];
92✔
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.
341
                    $useWrappedType = $queryNormalizationContext !== $mutationNormalizationContext;
92✔
342

343
                    $wrappedOperationName = $operationName;
92✔
344

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

349
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
92✔
350

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

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

365
                        return $fields;
6✔
366
                    }
367

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

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

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

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

386
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
304✔
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

© 2026 Coveralls, Inc