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

api-platform / core / 7970391001

20 Feb 2024 08:19AM UTC coverage: 63.778% (-0.02%) from 63.802%
7970391001

push

github

web-flow
feat(graphql): support nullable embedded relations in GraphQL types (#6100)

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

43 existing lines in 4 files now uncovered.

17092 of 26799 relevant lines covered (63.78%)

29.73 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 readonly ContainerInterface $fieldsBuilderLocator, private readonly Pagination $pagination)
45
    {
46
        $this->defaultFieldResolver = $defaultFieldResolver;
×
47
    }
48

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

60
        if ($operation instanceof Mutation) {
×
61
            $shortName = $operationName.ucfirst($shortName);
×
62
        }
63

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

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

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

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

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

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

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

107
        return $resourceObjectType;
×
108
    }
109

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

121
            return $nodeInterface;
×
122
        }
123

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

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

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

144
        $this->typesContainer->set('Node', $nodeInterface);
×
145

146
        return $nodeInterface;
×
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
    {
164
        $namedType = GraphQLType::getNamedType($resourceType);
×
165
        // graphql-php 15: name() exists
166
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
×
167
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
×
168

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

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

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

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

187
        return $resourcePaginatedCollectionType;
×
188
    }
189

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

194
        if ($this->typesContainer->has($enumName)) {
×
195
            return $this->typesContainer->get($enumName);
×
196
        }
197

198
        /** @var FieldsBuilderEnumInterface|FieldsBuilderInterface $fieldsBuilder */
199
        $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
×
200
        $enumCases = [];
×
201
        // Remove the condition in API Platform 4.
202
        if ($fieldsBuilder instanceof FieldsBuilderEnumInterface) {
×
203
            $enumCases = $fieldsBuilder->getEnumFields($operation->getClass());
×
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

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

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

219
        return $enumType;
×
220
    }
221

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

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

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

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

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

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

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

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

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

303
        return null;
×
304
    }
305

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

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

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

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

329
                    try {
NEW
330
                        $mutationNormalizationContext = $operation instanceof Mutation || $operation instanceof Subscription ? ($resourceMetadataCollection->getOperation($operationName)->getNormalizationContext() ?? []) : [];
×
NEW
331
                    } catch (OperationNotFoundException) {
×
NEW
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.
NEW
336
                    $useWrappedType = $queryNormalizationContext !== $mutationNormalizationContext;
×
337

NEW
338
                    $wrappedOperationName = $operationName;
×
339

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

NEW
344
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
×
345

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

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

NEW
360
                        return $fields;
×
361
                    }
362

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

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

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

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

NEW
381
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
×
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