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

api-platform / core / 9562658349

18 Jun 2024 09:35AM UTC coverage: 62.637% (+0.4%) from 62.272%
9562658349

push

github

soyuka
Merge 3.4

52 of 55 new or added lines in 6 files covered. (94.55%)

236 existing lines in 20 files now uncovered.

11016 of 17587 relevant lines covered (62.64%)

60.45 hits per line

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

86.56
/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\MetadataAwareNameConverter;
42
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
43

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

53
    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)
54
    {
55
        if ($typeBuilder instanceof TypeBuilderInterface) {
32✔
UNCOV
56
            @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);
×
57
        }
58
        if ($typeBuilder instanceof TypeBuilderEnumInterface) {
32✔
UNCOV
59
            @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);
×
60
        }
61
        $this->typeBuilder = $typeBuilder;
32✔
62
    }
63

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

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

87
        $fieldName = lcfirst('item_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
32✔
88

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

94
            return [$fieldName => array_merge($fieldConfiguration, $configuration)];
32✔
95
        }
96

UNCOV
97
        return [];
×
98
    }
99

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

109
        $fieldName = lcfirst('collection_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
32✔
110

111
        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)) {
32✔
112
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
32✔
113
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
32✔
114
            $configuration['args'] = $args ?: $configuration['args'] ?? $fieldConfiguration['args'] + $extraArgs;
32✔
115

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

UNCOV
119
        return [];
×
120
    }
121

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

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

135
        $mutationFields[$operation->getName().$operation->getShortName()] = $fieldConfiguration ?? [];
32✔
136

137
        return $mutationFields;
32✔
138
    }
139

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

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

153
        if (!$fieldConfiguration) {
32✔
UNCOV
154
            return [];
×
155
        }
156

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

163
        $subscriptionFields[$subscriptionName.$operation->getShortName().'Subscribe'] = $fieldConfiguration;
32✔
164

165
        return $subscriptionFields;
32✔
166
    }
167

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

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

UNCOV
184
            return [];
×
185
        }
186

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

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

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

UNCOV
203
            return $fields;
×
204
        }
205

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

213
        ++$depth; // increment the depth for the call to getResourceFieldConfiguration.
32✔
214

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

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

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

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

247
        return $fields;
32✔
248
    }
249

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

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

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

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

278
        return $enumCases;
4✔
279
    }
280

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

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

294
        /*
295
         * This is @experimental, read the comment on the parameterToObjectType function as additional information.
296
         */
297
        foreach ($operation->getParameters() ?? [] as $parameter) {
32✔
298
            $key = $parameter->getKey();
32✔
299

300
            if (str_contains($key, ':property')) {
32✔
301
                if (!($filterId = $parameter->getFilter()) || !$this->filterLocator->has($filterId)) {
32✔
UNCOV
302
                    continue;
×
303
                }
304

305
                $parsedKey = explode('[:property]', $key);
32✔
306
                $flattenFields = [];
32✔
307
                foreach ($this->filterLocator->get($filterId)->getDescription($operation->getClass()) as $key => $value) {
32✔
308
                    $values = [];
32✔
309
                    parse_str($key, $values);
32✔
310
                    if (isset($values[$parsedKey[0]])) {
32✔
311
                        $values = $values[$parsedKey[0]];
32✔
312
                    }
313

314
                    $name = key($values);
32✔
315
                    $flattenFields[] = ['name' => $name, 'required' => $value['required'] ?? null, 'description' => $value['description'] ?? null, 'leafs' => $values[$name], 'type' => $value['type'] ?? 'string'];
32✔
316
                }
317

318
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0]);
32✔
319
                continue;
32✔
320
            }
321

322
            $args[$key] = ['type' => GraphQLType::string()];
32✔
323

324
            if ($parameter->getRequired()) {
32✔
UNCOV
325
                $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
326
            }
327
        }
328

329
        return $args;
32✔
330
    }
331

332
    /**
333
     * Transform the result of a parse_str to a GraphQL object type.
334
     * We should consider merging getFilterArgs and this, `getFilterArgs` uses `convertType` whereas we assume that parameters have only scalar types.
335
     * Note that this method has a lower complexity then the `getFilterArgs` one.
336
     * TODO: Is there a use case with an argument being a complex type (eg: a Resource, Enum etc.)?
337
     *
338
     * @param array<array{name: string, required: bool|null, description: string|null, leafs: string|array, type: string}> $flattenFields
339
     */
340
    private function parameterToObjectType(array $flattenFields, string $name): InputObjectType
341
    {
342
        $fields = [];
32✔
343
        foreach ($flattenFields as $field) {
32✔
344
            $key = $field['name'];
32✔
345
            $type = $this->getParameterType(\in_array($field['type'], Type::$builtinTypes, true) ? new Type($field['type'], !$field['required']) : new Type('object', !$field['required'], $field['type']));
32✔
346

347
            if (\is_array($l = $field['leafs'])) {
32✔
348
                if (0 === key($l)) {
32✔
349
                    $key = $key;
32✔
350
                    $type = GraphQLType::listOf($type);
32✔
351
                } else {
352
                    $n = [];
32✔
353
                    foreach ($field['leafs'] as $l => $value) {
32✔
354
                        $n[] = ['required' => null, 'name' => $l, 'leafs' => $value, 'type' => 'string', 'description' => null];
32✔
355
                    }
356

357
                    $type = $this->parameterToObjectType($n, $key);
32✔
358
                    if (isset($fields[$key]) && ($t = $fields[$key]['type']) instanceof InputObjectType) {
32✔
359
                        $t = $fields[$key]['type'];
32✔
360
                        $t->config['fields'] = array_merge($t->config['fields'], $type->config['fields']);
32✔
361
                        $type = $t;
32✔
362
                    }
363
                }
364
            }
365

366
            if ($field['required']) {
32✔
UNCOV
367
                $type = GraphQLType::nonNull($type);
×
368
            }
369

370
            if (isset($fields[$key])) {
32✔
371
                if ($type instanceof ListOfType) {
32✔
372
                    $key .= '_list';
32✔
373
                }
374
            }
375

376
            $fields[$key] = ['type' => $type, 'name' => $key];
32✔
377
        }
378

379
        return new InputObjectType(['name' => $name, 'fields' => $fields]);
32✔
380
    }
381

382
    /**
383
     * A simplified version of convert type that does not support resources.
384
     */
385
    private function getParameterType(Type $type): GraphQLType
386
    {
387
        return match ($type->getBuiltinType()) {
32✔
388
            Type::BUILTIN_TYPE_BOOL => GraphQLType::boolean(),
32✔
389
            Type::BUILTIN_TYPE_INT => GraphQLType::int(),
32✔
390
            Type::BUILTIN_TYPE_FLOAT => GraphQLType::float(),
32✔
391
            Type::BUILTIN_TYPE_STRING => GraphQLType::string(),
32✔
392
            Type::BUILTIN_TYPE_ARRAY => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
32✔
393
            Type::BUILTIN_TYPE_ITERABLE => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
32✔
394
            Type::BUILTIN_TYPE_OBJECT => GraphQLType::string(),
32✔
395
            default => GraphQLType::string(),
32✔
396
        };
32✔
397
    }
398

399
    /**
400
     * Get the field configuration of a resource.
401
     *
402
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
403
     */
404
    private function getResourceFieldConfiguration(?string $property, ?string $fieldDescription, ?string $deprecationReason, Type $type, string $rootResource, bool $input, Operation $rootOperation, int $depth = 0, bool $forceNullable = false): ?array
405
    {
406
        try {
407
            $isCollectionType = $this->typeBuilder->isCollection($type);
32✔
408

409
            if (
410
                $isCollectionType
32✔
411
                && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
32✔
412
            ) {
413
                $resourceClass = $collectionValueType->getClassName();
32✔
414
            } else {
415
                $resourceClass = $type->getClassName();
32✔
416
            }
417

418
            $resourceOperation = $rootOperation;
32✔
419
            if ($resourceClass && $depth >= 1 && $this->resourceClassResolver->isResourceClass($resourceClass)) {
32✔
420
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
UNCOV
421
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
×
422
            }
423

424
            if (!$resourceOperation instanceof Operation) {
32✔
UNCOV
425
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
426
            }
427

428
            $graphqlType = $this->convertType($type, $input, $resourceOperation, $rootOperation, $resourceClass ?? '', $rootResource, $property, $depth, $forceNullable);
32✔
429

430
            $graphqlWrappedType = $graphqlType;
32✔
431
            if ($graphqlType instanceof WrappingType) {
32✔
432
                if (method_exists($graphqlType, 'getInnermostType')) {
32✔
433
                    $graphqlWrappedType = $graphqlType->getInnermostType();
32✔
434
                } else {
UNCOV
435
                    $graphqlWrappedType = $graphqlType->getWrappedType(true);
×
436
                }
437
            }
438
            $isStandardGraphqlType = \in_array($graphqlWrappedType, GraphQLType::getStandardTypes(), true);
32✔
439
            if ($isStandardGraphqlType) {
32✔
440
                $resourceClass = '';
32✔
441
            }
442

443
            // Check mercure attribute if it's a subscription at the root level.
444
            if ($rootOperation instanceof Subscription && null === $property && !$rootOperation->getMercure()) {
32✔
UNCOV
445
                return null;
×
446
            }
447

448
            $args = [];
32✔
449

450
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType && $isCollectionType) {
32✔
451
                if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
32✔
452
                    $args = $this->getGraphQlPaginationArgs($resourceOperation);
32✔
453
                }
454

455
                $args = $this->getFilterArgs($args, $resourceClass, $rootResource, $resourceOperation, $rootOperation, $property, $depth);
32✔
456
            }
457

458
            if ($this->itemResolverFactory instanceof ResolverFactory) {
32✔
459
                if ($isStandardGraphqlType || $input) {
24✔
460
                    $resolve = null;
24✔
461
                } else {
462
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation, $this->propertyMetadataFactory);
24✔
463
                }
464
            } else {
465
                if ($isStandardGraphqlType || $input) {
8✔
466
                    $resolve = null;
8✔
467
                } elseif (($rootOperation instanceof Mutation || $rootOperation instanceof Subscription) && $depth <= 0) {
8✔
468
                    $resolve = $rootOperation instanceof Mutation ? ($this->itemMutationResolverFactory)($resourceClass, $rootResource, $resourceOperation) : ($this->itemSubscriptionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
8✔
469
                } elseif ($this->typeBuilder->isCollection($type)) {
8✔
UNCOV
470
                    $resolve = ($this->collectionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
8✔
471
                } else {
UNCOV
472
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation);
8✔
473
                }
474
            }
475

476
            return [
32✔
477
                'type' => $graphqlType,
32✔
478
                'description' => $fieldDescription,
32✔
479
                'args' => $args,
32✔
480
                'resolve' => $resolve,
32✔
481
                'deprecationReason' => $deprecationReason,
32✔
482
            ];
32✔
483
        } catch (InvalidTypeException) {
4✔
484
            // just ignore invalid types
485
        }
486

487
        return null;
4✔
488
    }
489

490
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
491
    {
492
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
32✔
493

494
        if ('cursor' === $paginationType) {
32✔
495
            return [
32✔
496
                'first' => [
32✔
497
                    'type' => GraphQLType::int(),
32✔
498
                    'description' => 'Returns the first n elements from the list.',
32✔
499
                ],
32✔
500
                'last' => [
32✔
501
                    'type' => GraphQLType::int(),
32✔
502
                    'description' => 'Returns the last n elements from the list.',
32✔
503
                ],
32✔
504
                'before' => [
32✔
505
                    'type' => GraphQLType::string(),
32✔
506
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
32✔
507
                ],
32✔
508
                'after' => [
32✔
509
                    'type' => GraphQLType::string(),
32✔
510
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
32✔
511
                ],
32✔
512
            ];
32✔
513
        }
514

515
        $paginationOptions = $this->pagination->getOptions();
32✔
516

517
        $args = [
32✔
518
            $paginationOptions['page_parameter_name'] => [
32✔
519
                'type' => GraphQLType::int(),
32✔
520
                'description' => 'Returns the current page.',
32✔
521
            ],
32✔
522
        ];
32✔
523

524
        if ($paginationOptions['client_items_per_page']) {
32✔
525
            $args[$paginationOptions['items_per_page_parameter_name']] = [
32✔
526
                'type' => GraphQLType::int(),
32✔
527
                'description' => 'Returns the number of items per page.',
32✔
528
            ];
32✔
529
        }
530

531
        return $args;
32✔
532
    }
533

534
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
535
    {
536
        if (null === $resourceClass) {
32✔
UNCOV
537
            return $args;
×
538
        }
539

540
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
32✔
541
            if (!$this->filterLocator->has($filterId)) {
32✔
UNCOV
542
                continue;
×
543
            }
544

545
            $entityClass = $resourceClass;
32✔
546
            if ($options = $resourceOperation->getStateOptions()) {
32✔
547
                if ($options instanceof Options && $options->getEntityClass()) {
32✔
548
                    $entityClass = $options->getEntityClass();
32✔
549
                }
550

551
                if ($options instanceof ODMOptions && $options->getDocumentClass()) {
32✔
552
                    $entityClass = $options->getDocumentClass();
32✔
553
                }
554
            }
555

556
            foreach ($this->filterLocator->get($filterId)->getDescription($entityClass) as $key => $description) {
32✔
557
                $nullable = isset($description['required']) ? !$description['required'] : true;
32✔
558
                $filterType = \in_array($description['type'], Type::$builtinTypes, true) ? new Type($description['type'], $nullable) : new Type('object', $nullable, $description['type']);
32✔
559
                $graphqlFilterType = $this->convertType($filterType, false, $resourceOperation, $rootOperation, $resourceClass, $rootResource, $property, $depth);
32✔
560

561
                if (str_ends_with($key, '[]')) {
32✔
562
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
32✔
563
                    $key = substr($key, 0, -2).'_list';
32✔
564
                }
565

566
                /** @var string $key */
567
                $key = str_replace('.', $this->nestingSeparator, $key);
32✔
568

569
                parse_str($key, $parsed);
32✔
570
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
32✔
UNCOV
571
                    $parsed = [$key => ''];
×
572
                }
573
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
32✔
574
                    $v = $graphqlFilterType;
32✔
575
                });
32✔
576
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
32✔
577
            }
578
        }
579

580
        return $this->convertFilterArgsToTypes($args);
32✔
581
    }
582

583
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
584
    {
585
        foreach ($parsed as $key => $value) {
32✔
586
            // Never override keys that cannot be merged
587
            if (isset($args[$key]) && !\is_array($args[$key])) {
32✔
588
                continue;
32✔
589
            }
590

591
            if (\is_array($value)) {
32✔
592
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
32✔
593
                if (!isset($value['#name'])) {
32✔
594
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
32✔
595
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
32✔
596
                }
597
            }
598

599
            $args[$key] = $value;
32✔
600
        }
601

602
        return $args;
32✔
603
    }
604

605
    private function convertFilterArgsToTypes(array $args): array
606
    {
607
        foreach ($args as $key => $value) {
32✔
608
            if (strpos($key, '.')) {
32✔
609
                // Declare relations/nested fields in a GraphQL compatible syntax.
610
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
UNCOV
611
                unset($args[$key]);
×
612
            }
613
        }
614

615
        foreach ($args as $key => $value) {
32✔
616
            if (!\is_array($value) || !isset($value['#name'])) {
32✔
617
                continue;
32✔
618
            }
619

620
            $name = $value['#name'];
32✔
621

622
            if ($this->typesContainer->has($name)) {
32✔
623
                $args[$key] = $this->typesContainer->get($name);
×
UNCOV
624
                continue;
×
625
            }
626

627
            unset($value['#name']);
32✔
628

629
            $filterArgType = GraphQLType::listOf(new InputObjectType([
32✔
630
                'name' => $name,
32✔
631
                'fields' => $this->convertFilterArgsToTypes($value),
32✔
632
            ]));
32✔
633

634
            $this->typesContainer->set($name, $filterArgType);
32✔
635

636
            $args[$key] = $filterArgType;
32✔
637
        }
638

639
        return $args;
32✔
640
    }
641

642
    /**
643
     * Converts a built-in type to its GraphQL equivalent.
644
     *
645
     * @throws InvalidTypeException
646
     */
647
    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
648
    {
649
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
32✔
650

651
        if (null === $graphqlType) {
32✔
652
            throw new InvalidTypeException(sprintf('The type "%s" is not supported.', $type->getBuiltinType()));
4✔
653
        }
654

655
        if (\is_string($graphqlType)) {
32✔
656
            if (!$this->typesContainer->has($graphqlType)) {
×
UNCOV
657
                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));
×
658
            }
659

UNCOV
660
            $graphqlType = $this->typesContainer->get($graphqlType);
×
661
        }
662

663
        if ($this->typeBuilder->isCollection($type)) {
32✔
664
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
32✔
665
                // Deprecated path, to remove in API Platform 4.
666
                if ($this->typeBuilder instanceof TypeBuilderInterface) {
32✔
UNCOV
667
                    return $this->typeBuilder->getResourcePaginatedCollectionType($graphqlType, $resourceClass, $resourceOperation);
×
668
                }
669

670
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
32✔
671
            }
672

673
            return GraphQLType::listOf($graphqlType);
32✔
674
        }
675

676
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
32✔
677
            ? $graphqlType
32✔
678
            : GraphQLType::nonNull($graphqlType);
32✔
679
    }
680

681
    private function normalizePropertyName(string $property, string $resourceClass): string
682
    {
683
        if (null === $this->nameConverter) {
32✔
UNCOV
684
            return $property;
×
685
        }
686
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
32✔
687
            return $this->nameConverter->normalize($property, $resourceClass);
32✔
688
        }
689

UNCOV
690
        return $this->nameConverter->normalize($property);
×
691
    }
692
}
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