• 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/FieldsBuilder.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\Doctrine\Odm\State\Options as ODMOptions;
17
use ApiPlatform\Doctrine\Orm\State\Options;
18
use ApiPlatform\GraphQl\Resolver\Factory\ResolverFactory;
19
use ApiPlatform\GraphQl\Resolver\Factory\ResolverFactoryInterface;
20
use ApiPlatform\GraphQl\Type\Definition\TypeInterface;
21
use ApiPlatform\Metadata\GraphQl\Mutation;
22
use ApiPlatform\Metadata\GraphQl\Operation;
23
use ApiPlatform\Metadata\GraphQl\Query;
24
use ApiPlatform\Metadata\GraphQl\Subscription;
25
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
26
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
27
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
28
use ApiPlatform\Metadata\ResourceClassResolverInterface;
29
use ApiPlatform\Metadata\Util\Inflector;
30
use ApiPlatform\State\Pagination\Pagination;
31
use GraphQL\Type\Definition\InputObjectType;
32
use GraphQL\Type\Definition\ListOfType;
33
use GraphQL\Type\Definition\NonNull;
34
use GraphQL\Type\Definition\NullableType;
35
use GraphQL\Type\Definition\Type as GraphQLType;
36
use GraphQL\Type\Definition\WrappingType;
37
use Psr\Container\ContainerInterface;
38
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
39
use Symfony\Component\PropertyInfo\Type;
40
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
41
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
42

43
/**
44
 * Builds the GraphQL fields.
45
 *
46
 * @author Alan Poulain <contact@alanpoulain.eu>
47
 */
48
final class FieldsBuilder implements FieldsBuilderInterface, FieldsBuilderEnumInterface
49
{
50
    private readonly ContextAwareTypeBuilderInterface|TypeBuilderEnumInterface|TypeBuilderInterface $typeBuilder;
51

52
    public function __construct(private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, private readonly ResourceClassResolverInterface $resourceClassResolver, private readonly TypesContainerInterface $typesContainer, ContextAwareTypeBuilderInterface|TypeBuilderEnumInterface|TypeBuilderInterface $typeBuilder, private readonly TypeConverterInterface $typeConverter, private readonly ResolverFactoryInterface $itemResolverFactory, private readonly ?ResolverFactoryInterface $collectionResolverFactory, private readonly ?ResolverFactoryInterface $itemMutationResolverFactory, private readonly ?ResolverFactoryInterface $itemSubscriptionResolverFactory, private readonly ContainerInterface $filterLocator, private readonly Pagination $pagination, private readonly ?NameConverterInterface $nameConverter, private readonly string $nestingSeparator)
53
    {
54
        if ($typeBuilder instanceof TypeBuilderInterface) {
×
55
            @trigger_error(sprintf('$typeBuilder argument of FieldsBuilder implementing "%s" is deprecated since API Platform 3.1. It has to implement "%s" instead.', TypeBuilderInterface::class, TypeBuilderEnumInterface::class), \E_USER_DEPRECATED);
×
56
        }
NEW
57
        if ($typeBuilder instanceof TypeBuilderEnumInterface) {
×
NEW
58
            @trigger_error(sprintf('$typeBuilder argument of TypeConverter implementing "%s" is deprecated since API Platform 3.3. It has to implement "%s" instead.', TypeBuilderEnumInterface::class, ContextAwareTypeBuilderInterface::class), \E_USER_DEPRECATED);
×
59
        }
UNCOV
60
        $this->typeBuilder = $typeBuilder;
×
61
    }
62

63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function getNodeQueryFields(): array
67
    {
68
        return [
×
69
            'type' => $this->typeBuilder->getNodeInterface(),
×
70
            'args' => [
×
71
                'id' => ['type' => GraphQLType::nonNull(GraphQLType::id())],
×
72
            ],
×
73
            'resolve' => ($this->itemResolverFactory)(),
×
74
        ];
×
75
    }
76

77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function getItemQueryFields(string $resourceClass, Operation $operation, array $configuration): array
81
    {
82
        if ($operation instanceof Query && $operation->getNested()) {
×
83
            return [];
×
84
        }
85

86
        $fieldName = lcfirst('item_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
×
87

88
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), new Type(Type::BUILTIN_TYPE_OBJECT, true, $resourceClass), $resourceClass, false, $operation)) {
×
89
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
×
90
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
×
91
            $configuration['args'] = $args ?: $configuration['args'] ?? ['id' => ['type' => GraphQLType::nonNull(GraphQLType::id())]] + $extraArgs;
×
92

93
            return [$fieldName => array_merge($fieldConfiguration, $configuration)];
×
94
        }
95

96
        return [];
×
97
    }
98

99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function getCollectionQueryFields(string $resourceClass, Operation $operation, array $configuration): array
103
    {
104
        if ($operation instanceof Query && $operation->getNested()) {
×
105
            return [];
×
106
        }
107

108
        $fieldName = lcfirst('collection_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
×
109

110
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), new Type(Type::BUILTIN_TYPE_OBJECT, false, null, true, null, new Type(Type::BUILTIN_TYPE_OBJECT, false, $resourceClass)), $resourceClass, false, $operation)) {
×
111
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
×
112
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
×
113
            $configuration['args'] = $args ?: $configuration['args'] ?? $fieldConfiguration['args'] + $extraArgs;
×
114

115
            return [Inflector::pluralize($fieldName) => array_merge($fieldConfiguration, $configuration)];
×
116
        }
117

118
        return [];
×
119
    }
120

121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function getMutationFields(string $resourceClass, Operation $operation): array
125
    {
126
        $mutationFields = [];
×
127
        $resourceType = new Type(Type::BUILTIN_TYPE_OBJECT, true, $resourceClass);
×
128
        $description = $operation->getDescription() ?? ucfirst("{$operation->getName()}s a {$operation->getShortName()}.");
×
129

130
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $description, $operation->getDeprecationReason(), $resourceType, $resourceClass, false, $operation)) {
×
131
            $fieldConfiguration['args'] += ['input' => $this->getResourceFieldConfiguration(null, null, $operation->getDeprecationReason(), $resourceType, $resourceClass, true, $operation)];
×
132
        }
133

134
        $mutationFields[$operation->getName().$operation->getShortName()] = $fieldConfiguration ?? [];
×
135

136
        return $mutationFields;
×
137
    }
138

139
    /**
140
     * {@inheritdoc}
141
     */
142
    public function getSubscriptionFields(string $resourceClass, Operation $operation): array
143
    {
144
        $subscriptionFields = [];
×
145
        $resourceType = new Type(Type::BUILTIN_TYPE_OBJECT, true, $resourceClass);
×
146
        $description = $operation->getDescription() ?? sprintf('Subscribes to the action event of a %s.', $operation->getShortName());
×
147

148
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $description, $operation->getDeprecationReason(), $resourceType, $resourceClass, false, $operation)) {
×
149
            $fieldConfiguration['args'] += ['input' => $this->getResourceFieldConfiguration(null, null, $operation->getDeprecationReason(), $resourceType, $resourceClass, true, $operation)];
×
150
        }
151

152
        if (!$fieldConfiguration) {
×
153
            return [];
×
154
        }
155

156
        $subscriptionName = $operation->getName();
×
157
        // TODO: 3.0 change this
158
        if ('update_subscription' === $subscriptionName) {
×
159
            $subscriptionName = 'update';
×
160
        }
161

162
        $subscriptionFields[$subscriptionName.$operation->getShortName().'Subscribe'] = $fieldConfiguration;
×
163

164
        return $subscriptionFields;
×
165
    }
166

167
    /**
168
     * {@inheritdoc}
169
     */
170
    public function getResourceObjectTypeFields(?string $resourceClass, Operation $operation, bool $input, int $depth = 0, ?array $ioMetadata = null): array
171
    {
172
        $fields = [];
×
173
        $idField = ['type' => GraphQLType::nonNull(GraphQLType::id())];
×
174
        $optionalIdField = ['type' => GraphQLType::id()];
×
175
        $clientMutationId = GraphQLType::string();
×
176
        $clientSubscriptionId = GraphQLType::string();
×
177

178
        if (null !== $ioMetadata && \array_key_exists('class', $ioMetadata) && null === $ioMetadata['class']) {
×
179
            if ($input) {
×
180
                return ['clientMutationId' => $clientMutationId];
×
181
            }
182

183
            return [];
×
184
        }
185

186
        if ($operation instanceof Subscription && $input) {
×
187
            return [
×
188
                'id' => $idField,
×
189
                'clientSubscriptionId' => $clientSubscriptionId,
×
190
            ];
×
191
        }
192

193
        if ('delete' === $operation->getName()) {
×
194
            $fields = [
×
195
                'id' => $idField,
×
196
            ];
×
197

198
            if ($input) {
×
199
                $fields['clientMutationId'] = $clientMutationId;
×
200
            }
201

202
            return $fields;
×
203
        }
204

205
        if (!$input || (!$operation->getResolver() && 'create' !== $operation->getName())) {
×
206
            $fields['id'] = $idField;
×
207
        }
208
        if ($input && $depth >= 1) {
×
209
            $fields['id'] = $optionalIdField;
×
210
        }
211

212
        ++$depth; // increment the depth for the call to getResourceFieldConfiguration.
×
213

214
        if (null !== $resourceClass) {
×
215
            foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
×
216
                $context = [
×
217
                    'normalization_groups' => $operation->getNormalizationContext()['groups'] ?? null,
×
218
                    'denormalization_groups' => $operation->getDenormalizationContext()['groups'] ?? null,
×
219
                ];
×
220
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property, $context);
×
221
                $propertyTypes = $propertyMetadata->getBuiltinTypes();
×
222

223
                if (
224
                    !$propertyTypes
×
225
                    || (!$input && false === $propertyMetadata->isReadable())
×
226
                    || ($input && false === $propertyMetadata->isWritable())
×
227
                ) {
228
                    continue;
×
229
                }
230

231
                // guess union/intersect types: check each type until finding a valid one
232
                foreach ($propertyTypes as $propertyType) {
×
233
                    if ($fieldConfiguration = $this->getResourceFieldConfiguration($property, $propertyMetadata->getDescription(), $propertyMetadata->getDeprecationReason(), $propertyType, $resourceClass, $input, $operation, $depth, null !== $propertyMetadata->getSecurity())) {
×
234
                        $fields['id' === $property ? '_id' : $this->normalizePropertyName($property, $resourceClass)] = $fieldConfiguration;
×
235
                        // stop at the first valid type
236
                        break;
×
237
                    }
238
                }
239
            }
240
        }
241

242
        if ($operation instanceof Mutation && $input) {
×
243
            $fields['clientMutationId'] = $clientMutationId;
×
244
        }
245

246
        return $fields;
×
247
    }
248

249
    private function isEnumClass(string $resourceClass): bool
250
    {
251
        return is_a($resourceClass, \BackedEnum::class, true);
×
252
    }
253

254
    /**
255
     * {@inheritdoc}
256
     */
257
    public function getEnumFields(string $enumClass): array
258
    {
259
        $rEnum = new \ReflectionEnum($enumClass);
×
260

261
        $enumCases = [];
×
262
        /* @var \ReflectionEnumUnitCase|\ReflectionEnumBackedCase */
263
        foreach ($rEnum->getCases() as $rCase) {
×
264
            if ($rCase instanceof \ReflectionEnumBackedCase) {
×
265
                $enumCase = ['value' => $rCase->getBackingValue()];
×
266
            } else {
267
                $enumCase = ['value' => $rCase->getValue()];
×
268
            }
269

270
            $propertyMetadata = $this->propertyMetadataFactory->create($enumClass, $rCase->getName());
×
271
            if ($enumCaseDescription = $propertyMetadata->getDescription()) {
×
272
                $enumCase['description'] = $enumCaseDescription;
×
273
            }
274
            $enumCases[$rCase->getName()] = $enumCase;
×
275
        }
276

277
        return $enumCases;
×
278
    }
279

280
    /**
281
     * {@inheritdoc}
282
     */
283
    public function resolveResourceArgs(array $args, Operation $operation): array
284
    {
285
        foreach ($args as $id => $arg) {
×
286
            if (!isset($arg['type'])) {
×
287
                throw new \InvalidArgumentException(sprintf('The argument "%s" of the custom operation "%s" in %s needs a "type" option.', $id, $operation->getName(), $operation->getShortName()));
×
288
            }
289

290
            $args[$id]['type'] = $this->typeConverter->resolveType($arg['type']);
×
291
        }
292

293
        return $args;
×
294
    }
295

296
    /**
297
     * Get the field configuration of a resource.
298
     *
299
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
300
     */
301
    private function getResourceFieldConfiguration(?string $property, ?string $fieldDescription, ?string $deprecationReason, Type $type, string $rootResource, bool $input, Operation $rootOperation, int $depth = 0, bool $forceNullable = false): ?array
302
    {
303
        try {
304
            $isCollectionType = $this->typeBuilder->isCollection($type);
×
305

306
            if (
307
                $isCollectionType
×
308
                && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
×
309
            ) {
310
                $resourceClass = $collectionValueType->getClassName();
×
311
            } else {
312
                $resourceClass = $type->getClassName();
×
313
            }
314

315
            $resourceOperation = $rootOperation;
×
316
            if ($resourceClass && $depth >= 1 && $this->resourceClassResolver->isResourceClass($resourceClass)) {
×
317
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
318
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
×
319
            }
320

321
            if (!$resourceOperation instanceof Operation) {
×
322
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
323
            }
324

325
            $graphqlType = $this->convertType($type, $input, $resourceOperation, $rootOperation, $resourceClass ?? '', $rootResource, $property, $depth, $forceNullable);
×
326

327
            $graphqlWrappedType = $graphqlType;
×
328
            if ($graphqlType instanceof WrappingType) {
×
329
                if (method_exists($graphqlType, 'getInnermostType')) {
×
330
                    $graphqlWrappedType = $graphqlType->getInnermostType();
×
331
                } else {
332
                    $graphqlWrappedType = $graphqlType->getWrappedType(true);
×
333
                }
334
            }
335
            $isStandardGraphqlType = \in_array($graphqlWrappedType, GraphQLType::getStandardTypes(), true);
×
336
            if ($isStandardGraphqlType) {
×
337
                $resourceClass = '';
×
338
            }
339

340
            // Check mercure attribute if it's a subscription at the root level.
341
            if ($rootOperation instanceof Subscription && null === $property && !$rootOperation->getMercure()) {
×
342
                return null;
×
343
            }
344

345
            $args = [];
×
346

347
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType && $isCollectionType) {
×
348
                if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
×
349
                    $args = $this->getGraphQlPaginationArgs($resourceOperation);
×
350
                }
351

352
                $args = $this->getFilterArgs($args, $resourceClass, $rootResource, $resourceOperation, $rootOperation, $property, $depth);
×
353
            }
354

355
            if ($this->itemResolverFactory instanceof ResolverFactory) {
×
356
                if ($isStandardGraphqlType || $input) {
×
357
                    $resolve = null;
×
358
                } else {
359
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation);
×
360
                }
361
            } else {
362
                if ($isStandardGraphqlType || $input) {
×
363
                    $resolve = null;
×
364
                } elseif (($rootOperation instanceof Mutation || $rootOperation instanceof Subscription) && $depth <= 0) {
×
365
                    $resolve = $rootOperation instanceof Mutation ? ($this->itemMutationResolverFactory)($resourceClass, $rootResource, $resourceOperation) : ($this->itemSubscriptionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
×
366
                } elseif ($this->typeBuilder->isCollection($type)) {
×
367
                    $resolve = ($this->collectionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
×
368
                } else {
369
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation);
×
370
                }
371
            }
372

373
            return [
×
374
                'type' => $graphqlType,
×
375
                'description' => $fieldDescription,
×
376
                'args' => $args,
×
377
                'resolve' => $resolve,
×
378
                'deprecationReason' => $deprecationReason,
×
379
            ];
×
380
        } catch (InvalidTypeException) {
×
381
            // just ignore invalid types
382
        }
383

384
        return null;
×
385
    }
386

387
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
388
    {
389
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
×
390

391
        if ('cursor' === $paginationType) {
×
392
            return [
×
393
                'first' => [
×
394
                    'type' => GraphQLType::int(),
×
395
                    'description' => 'Returns the first n elements from the list.',
×
396
                ],
×
397
                'last' => [
×
398
                    'type' => GraphQLType::int(),
×
399
                    'description' => 'Returns the last n elements from the list.',
×
400
                ],
×
401
                'before' => [
×
402
                    'type' => GraphQLType::string(),
×
403
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
×
404
                ],
×
405
                'after' => [
×
406
                    'type' => GraphQLType::string(),
×
407
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
×
408
                ],
×
409
            ];
×
410
        }
411

412
        $paginationOptions = $this->pagination->getOptions();
×
413

414
        $args = [
×
415
            $paginationOptions['page_parameter_name'] => [
×
416
                'type' => GraphQLType::int(),
×
417
                'description' => 'Returns the current page.',
×
418
            ],
×
419
        ];
×
420

421
        if ($paginationOptions['client_items_per_page']) {
×
422
            $args[$paginationOptions['items_per_page_parameter_name']] = [
×
423
                'type' => GraphQLType::int(),
×
424
                'description' => 'Returns the number of items per page.',
×
425
            ];
×
426
        }
427

428
        return $args;
×
429
    }
430

431
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
432
    {
433
        if (null === $resourceClass) {
×
434
            return $args;
×
435
        }
436

437
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
×
438
            if (!$this->filterLocator->has($filterId)) {
×
439
                continue;
×
440
            }
441

442
            $entityClass = $resourceClass;
×
443
            if ($options = $resourceOperation->getStateOptions()) {
×
444
                if ($options instanceof Options && $options->getEntityClass()) {
×
445
                    $entityClass = $options->getEntityClass();
×
446
                }
447

448
                if ($options instanceof ODMOptions && $options->getDocumentClass()) {
×
449
                    $entityClass = $options->getDocumentClass();
×
450
                }
451
            }
452

453
            foreach ($this->filterLocator->get($filterId)->getDescription($entityClass) as $key => $value) {
×
454
                $nullable = isset($value['required']) ? !$value['required'] : true;
×
455
                $filterType = \in_array($value['type'], Type::$builtinTypes, true) ? new Type($value['type'], $nullable) : new Type('object', $nullable, $value['type']);
×
456
                $graphqlFilterType = $this->convertType($filterType, false, $resourceOperation, $rootOperation, $resourceClass, $rootResource, $property, $depth);
×
457

458
                if (str_ends_with($key, '[]')) {
×
459
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
×
460
                    $key = substr($key, 0, -2).'_list';
×
461
                }
462

463
                /** @var string $key */
464
                $key = str_replace('.', $this->nestingSeparator, $key);
×
465

466
                parse_str($key, $parsed);
×
467
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
×
468
                    $parsed = [$key => ''];
×
469
                }
470
                array_walk_recursive($parsed, static function (&$value) use ($graphqlFilterType): void {
×
471
                    $value = $graphqlFilterType;
×
472
                });
×
473
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
×
474
            }
475
        }
476

477
        return $this->convertFilterArgsToTypes($args);
×
478
    }
479

480
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
481
    {
482
        foreach ($parsed as $key => $value) {
×
483
            // Never override keys that cannot be merged
484
            if (isset($args[$key]) && !\is_array($args[$key])) {
×
485
                continue;
×
486
            }
487

488
            if (\is_array($value)) {
×
489
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
×
490
                if (!isset($value['#name'])) {
×
491
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
×
492
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
×
493
                }
494
            }
495

496
            $args[$key] = $value;
×
497
        }
498

499
        return $args;
×
500
    }
501

502
    private function convertFilterArgsToTypes(array $args): array
503
    {
504
        foreach ($args as $key => $value) {
×
505
            if (strpos($key, '.')) {
×
506
                // Declare relations/nested fields in a GraphQL compatible syntax.
507
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
508
                unset($args[$key]);
×
509
            }
510
        }
511

512
        foreach ($args as $key => $value) {
×
513
            if (!\is_array($value) || !isset($value['#name'])) {
×
514
                continue;
×
515
            }
516

517
            $name = $value['#name'];
×
518

519
            if ($this->typesContainer->has($name)) {
×
520
                $args[$key] = $this->typesContainer->get($name);
×
521
                continue;
×
522
            }
523

524
            unset($value['#name']);
×
525

526
            $filterArgType = GraphQLType::listOf(new InputObjectType([
×
527
                'name' => $name,
×
528
                'fields' => $this->convertFilterArgsToTypes($value),
×
529
            ]));
×
530

531
            $this->typesContainer->set($name, $filterArgType);
×
532

533
            $args[$key] = $filterArgType;
×
534
        }
535

536
        return $args;
×
537
    }
538

539
    /**
540
     * Converts a built-in type to its GraphQL equivalent.
541
     *
542
     * @throws InvalidTypeException
543
     */
544
    private function convertType(Type $type, bool $input, Operation $resourceOperation, Operation $rootOperation, string $resourceClass, string $rootResource, ?string $property, int $depth, bool $forceNullable = false): GraphQLType|ListOfType|NonNull
545
    {
546
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
×
547

548
        if (null === $graphqlType) {
×
549
            throw new InvalidTypeException(sprintf('The type "%s" is not supported.', $type->getBuiltinType()));
×
550
        }
551

552
        if (\is_string($graphqlType)) {
×
553
            if (!$this->typesContainer->has($graphqlType)) {
×
554
                throw new InvalidTypeException(sprintf('The GraphQL type %s is not valid. Valid types are: %s. Have you registered this type by implementing %s?', $graphqlType, implode(', ', array_keys($this->typesContainer->all())), TypeInterface::class));
×
555
            }
556

557
            $graphqlType = $this->typesContainer->get($graphqlType);
×
558
        }
559

560
        if ($this->typeBuilder->isCollection($type)) {
×
561
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
×
562
                // Deprecated path, to remove in API Platform 4.
563
                if ($this->typeBuilder instanceof TypeBuilderInterface) {
×
564
                    return $this->typeBuilder->getResourcePaginatedCollectionType($graphqlType, $resourceClass, $resourceOperation);
×
565
                }
566

567
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
×
568
            }
569

570
            return GraphQLType::listOf($graphqlType);
×
571
        }
572

573
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
×
574
            ? $graphqlType
×
575
            : GraphQLType::nonNull($graphqlType);
×
576
    }
577

578
    private function normalizePropertyName(string $property, string $resourceClass): string
579
    {
580
        if (null === $this->nameConverter) {
×
581
            return $property;
×
582
        }
583
        if ($this->nameConverter instanceof AdvancedNameConverterInterface) {
×
584
            return $this->nameConverter->normalize($property, $resourceClass);
×
585
        }
586

587
        return $this->nameConverter->normalize($property);
×
588
    }
589
}
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