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

api-platform / core / 10014117656

19 Jul 2024 08:44PM UTC coverage: 7.856% (-56.3%) from 64.185%
10014117656

push

github

soyuka
Merge branch 'sf/remove-flag'

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

10505 existing lines in 362 files now uncovered.

12705 of 161727 relevant lines covered (7.86%)

26.85 hits per line

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

94.85
/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 readonly ContainerInterface $fieldsBuilderLocator, private readonly Pagination $pagination)
45
    {
UNCOV
46
        $this->defaultFieldResolver = $defaultFieldResolver;
441✔
47
    }
48

49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function getResourceObjectType(ResourceMetadataCollection $resourceMetadataCollection, Operation $operation, ?ApiProperty $propertyMetadata = null, array $context = []): GraphQLType
53
    {
UNCOV
54
        $shortName = $operation->getShortName();
435✔
UNCOV
55
        $operationName = $operation->getName();
435✔
UNCOV
56
        $input = $context['input'];
435✔
UNCOV
57
        $depth = $context['depth'] ?? 0;
435✔
UNCOV
58
        $wrapped = $context['wrapped'] ?? false;
435✔
59

UNCOV
60
        if ($operation instanceof Mutation) {
435✔
UNCOV
61
            $shortName = $operationName.ucfirst($shortName);
411✔
62
        }
63

UNCOV
64
        if ($operation instanceof Subscription) {
435✔
UNCOV
65
            $shortName = $operationName.ucfirst($shortName).'Subscription';
408✔
66
        }
67

UNCOV
68
        if ($input) {
435✔
UNCOV
69
            if ($depth > 0) {
411✔
70
                $shortName .= 'Nested';
18✔
71
            }
UNCOV
72
            $shortName .= 'Input';
411✔
UNCOV
73
        } elseif ($operation instanceof Mutation || $operation instanceof Subscription) {
435✔
UNCOV
74
            if ($depth > 0) {
411✔
75
                $shortName .= 'Nested';
12✔
76
            }
UNCOV
77
            $shortName .= 'Payload';
411✔
78
        }
79

UNCOV
80
        if ('item_query' === $operationName || 'collection_query' === $operationName) {
435✔
81
            // Test if the collection/item has different groups
UNCOV
82
            if ($resourceMetadataCollection->getOperation($operation instanceof CollectionOperationInterface ? 'item_query' : 'collection_query')->getNormalizationContext() !== $operation->getNormalizationContext()) {
435✔
UNCOV
83
                $shortName .= $operation instanceof CollectionOperationInterface ? 'Collection' : 'Item';
408✔
84
            }
85
        }
86

UNCOV
87
        if ($wrapped && ($operation instanceof Mutation || $operation instanceof Subscription)) {
435✔
88
            $shortName .= 'Data';
30✔
89
        }
90

UNCOV
91
        $resourceObjectType = null;
435✔
UNCOV
92
        if (!$this->typesContainer->has($shortName)) {
435✔
UNCOV
93
            $resourceObjectType = $this->getResourceObjectTypeConfiguration($shortName, $resourceMetadataCollection, $operation, $context);
435✔
UNCOV
94
            $this->typesContainer->set($shortName, $resourceObjectType);
435✔
95
        }
96

UNCOV
97
        $resourceObjectType = $resourceObjectType ?? $this->typesContainer->get($shortName);
435✔
UNCOV
98
        if (!($resourceObjectType instanceof ObjectType || $resourceObjectType instanceof NonNull || $resourceObjectType instanceof InputObjectType)) {
435✔
99
            throw new \LogicException(sprintf('Expected GraphQL type "%s" to be %s.', $shortName, implode('|', [ObjectType::class, NonNull::class, InputObjectType::class])));
×
100
        }
101

UNCOV
102
        $required = $propertyMetadata?->isRequired() ?? true;
435✔
UNCOV
103
        if ($required && $input) {
435✔
UNCOV
104
            $resourceObjectType = GraphQLType::nonNull($resourceObjectType);
411✔
105
        }
106

UNCOV
107
        return $resourceObjectType;
435✔
108
    }
109

110
    /**
111
     * {@inheritdoc}
112
     */
113
    public function getNodeInterface(): InterfaceType
114
    {
UNCOV
115
        if ($this->typesContainer->has('Node')) {
435✔
UNCOV
116
            $nodeInterface = $this->typesContainer->get('Node');
435✔
UNCOV
117
            if (!$nodeInterface instanceof InterfaceType) {
435✔
118
                throw new \LogicException(sprintf('Expected GraphQL type "Node" to be %s.', InterfaceType::class));
×
119
            }
120

UNCOV
121
            return $nodeInterface;
435✔
122
        }
123

UNCOV
124
        $nodeInterface = new InterfaceType([
435✔
UNCOV
125
            'name' => 'Node',
435✔
UNCOV
126
            'description' => 'A node, according to the Relay specification.',
435✔
UNCOV
127
            'fields' => [
435✔
UNCOV
128
                'id' => [
435✔
UNCOV
129
                    'type' => GraphQLType::nonNull(GraphQLType::id()),
435✔
UNCOV
130
                    'description' => 'The id of this node.',
435✔
UNCOV
131
                ],
435✔
UNCOV
132
            ],
435✔
UNCOV
133
            'resolveType' => function ($value): ?GraphQLType {
435✔
134
                if (!isset($value[ItemNormalizer::ITEM_RESOURCE_CLASS_KEY])) {
3✔
135
                    return null;
×
136
                }
137

138
                $shortName = (new \ReflectionClass($value[ItemNormalizer::ITEM_RESOURCE_CLASS_KEY]))->getShortName();
3✔
139

140
                return $this->typesContainer->has($shortName) ? $this->typesContainer->get($shortName) : null;
3✔
UNCOV
141
            },
435✔
UNCOV
142
        ]);
435✔
143

UNCOV
144
        $this->typesContainer->set('Node', $nodeInterface);
435✔
145

UNCOV
146
        return $nodeInterface;
435✔
147
    }
148

149
    /**
150
     * {@inheritdoc}
151
     */
152
    public function getResourcePaginatedCollectionType(GraphQLType $resourceType, string $resourceClass, Operation $operation): GraphQLType
153
    {
154
        @trigger_error('Using getResourcePaginatedCollectionType method of TypeBuilder is deprecated since API Platform 3.1. Use getPaginatedCollectionType method instead.', \E_USER_DEPRECATED);
×
155

156
        return $this->getPaginatedCollectionType($resourceType, $operation);
×
157
    }
158

159
    /**
160
     * {@inheritdoc}
161
     */
162
    public function getPaginatedCollectionType(GraphQLType $resourceType, Operation $operation): GraphQLType
163
    {
UNCOV
164
        $namedType = GraphQLType::getNamedType($resourceType);
414✔
165
        // graphql-php 15: name() exists
UNCOV
166
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
414✔
UNCOV
167
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
414✔
168

UNCOV
169
        $connectionTypeKey = sprintf('%s%sConnection', $shortName, ucfirst($paginationType));
414✔
UNCOV
170
        if ($this->typesContainer->has($connectionTypeKey)) {
414✔
UNCOV
171
            return $this->typesContainer->get($connectionTypeKey);
408✔
172
        }
173

UNCOV
174
        $fields = 'cursor' === $paginationType ?
414✔
UNCOV
175
            $this->getCursorBasedPaginationFields($resourceType) :
414✔
UNCOV
176
            $this->getPageBasedPaginationFields($resourceType);
408✔
177

UNCOV
178
        $configuration = [
414✔
UNCOV
179
            'name' => $connectionTypeKey,
414✔
UNCOV
180
            'description' => sprintf("%s connection for $shortName.", ucfirst($paginationType)),
414✔
UNCOV
181
            'fields' => $fields,
414✔
UNCOV
182
        ];
414✔
183

UNCOV
184
        $resourcePaginatedCollectionType = new ObjectType($configuration);
414✔
UNCOV
185
        $this->typesContainer->set($connectionTypeKey, $resourcePaginatedCollectionType);
414✔
186

UNCOV
187
        return $resourcePaginatedCollectionType;
414✔
188
    }
189

190
    public function getEnumType(Operation $operation): GraphQLType
191
    {
UNCOV
192
        $enumName = $operation->getShortName();
16✔
193

UNCOV
194
        if ($this->typesContainer->has($enumName)) {
16✔
195
            return $this->typesContainer->get($enumName);
10✔
196
        }
197

198
        /** @var FieldsBuilderEnumInterface|FieldsBuilderInterface $fieldsBuilder */
UNCOV
199
        $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
16✔
UNCOV
200
        $enumCases = [];
16✔
201
        // Remove the condition in API Platform 4.
UNCOV
202
        if ($fieldsBuilder instanceof FieldsBuilderEnumInterface) {
16✔
UNCOV
203
            $enumCases = $fieldsBuilder->getEnumFields($operation->getClass());
16✔
204
        } else {
205
            @trigger_error(sprintf('api_platform.graphql.fields_builder service implementing "%s" is deprecated since API Platform 3.1. It has to implement "%s" instead.', FieldsBuilderInterface::class, FieldsBuilderEnumInterface::class), \E_USER_DEPRECATED);
×
206
        }
207

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

UNCOV
216
        $enumType = new EnumType($enumConfig);
16✔
UNCOV
217
        $this->typesContainer->set($enumName, $enumType);
16✔
218

UNCOV
219
        return $enumType;
16✔
220
    }
221

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

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

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

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

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

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

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

UNCOV
286
        return [
408✔
UNCOV
287
            'collection' => GraphQLType::listOf($resourceType),
408✔
UNCOV
288
            'paginationInfo' => GraphQLType::nonNull($paginationInfoObjectType),
408✔
UNCOV
289
        ];
408✔
290
    }
291

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

303
        return null;
×
304
    }
305

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

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

UNCOV
319
        $wrapData = !$wrapped && ($operation instanceof Mutation || $operation instanceof Subscription) && !$input && $depth < 1;
435✔
320

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

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

338
                    $wrappedOperationName = $operationName;
131✔
339

340
                    if (!$useWrappedType) {
131✔
341
                        $wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
107✔
342
                    }
343

344
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
131✔
345

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

354
                    if ($operation instanceof Subscription) {
131✔
355
                        $fields['clientSubscriptionId'] = GraphQLType::string();
9✔
356
                        if ($operation->getMercure()) {
9✔
357
                            $fields['mercureUrl'] = GraphQLType::string();
9✔
358
                        }
359

360
                        return $fields;
9✔
361
                    }
362

363
                    return $fields + ['clientMutationId' => GraphQLType::string()];
128✔
364
                }
365

UNCOV
366
                $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
417✔
UNCOV
367
                $fields = $fieldsBuilder->getResourceObjectTypeFields($resourceClass, $operation, $input, $depth, $ioMetadata);
417✔
368

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

UNCOV
376
                return $fields;
417✔
UNCOV
377
            },
435✔
UNCOV
378
            'interfaces' => $wrapData ? [] : [$this->getNodeInterface()],
435✔
UNCOV
379
        ];
435✔
380

UNCOV
381
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
435✔
382
    }
383
}
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