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

api-platform / core / 10027319583

21 Jul 2024 09:36AM UTC coverage: 7.847%. Remained the same
10027319583

push

github

web-flow
ci: fix naming of Windows Behat matrix line (#6489)

12688 of 161690 relevant lines covered (7.85%)

26.88 hits per line

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

91.72
/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\InflectorInterface;
26
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
27
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
28
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
29
use ApiPlatform\Metadata\ResourceClassResolverInterface;
30
use ApiPlatform\Metadata\Util\Inflector;
31
use ApiPlatform\State\Pagination\Pagination;
32
use GraphQL\Type\Definition\InputObjectType;
33
use GraphQL\Type\Definition\ListOfType;
34
use GraphQL\Type\Definition\NonNull;
35
use GraphQL\Type\Definition\NullableType;
36
use GraphQL\Type\Definition\Type as GraphQLType;
37
use GraphQL\Type\Definition\WrappingType;
38
use Psr\Container\ContainerInterface;
39
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
40
use Symfony\Component\PropertyInfo\Type;
41
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
42
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
43
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
44

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

54
    public function __construct(private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, private readonly ResourceClassResolverInterface $resourceClassResolver, private readonly TypesContainerInterface $typesContainer, ContextAwareTypeBuilderInterface $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, private readonly ?InflectorInterface $inflector = new Inflector())
55
    {
56
        $this->typeBuilder = $typeBuilder;
441✔
57
    }
58

59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function getNodeQueryFields(): array
63
    {
64
        return [
435✔
65
            'type' => $this->typeBuilder->getNodeInterface(),
435✔
66
            'args' => [
435✔
67
                'id' => ['type' => GraphQLType::nonNull(GraphQLType::id())],
435✔
68
            ],
435✔
69
            'resolve' => ($this->itemResolverFactory)(),
435✔
70
        ];
435✔
71
    }
72

73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function getItemQueryFields(string $resourceClass, Operation $operation, array $configuration): array
77
    {
78
        if ($operation instanceof Query && $operation->getNested()) {
435✔
79
            return [];
435✔
80
        }
81

82
        $fieldName = lcfirst('item_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
432✔
83

84
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), new Type(Type::BUILTIN_TYPE_OBJECT, true, $resourceClass), $resourceClass, false, $operation)) {
432✔
85
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
432✔
86
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
432✔
87
            $configuration['args'] = $args ?: $configuration['args'] ?? ['id' => ['type' => GraphQLType::nonNull(GraphQLType::id())]] + $extraArgs;
432✔
88

89
            return [$fieldName => array_merge($fieldConfiguration, $configuration)];
432✔
90
        }
91

92
        return [];
×
93
    }
94

95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function getCollectionQueryFields(string $resourceClass, Operation $operation, array $configuration): array
99
    {
100
        if ($operation instanceof Query && $operation->getNested()) {
435✔
101
            return [];
435✔
102
        }
103

104
        $fieldName = lcfirst('collection_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
435✔
105

106
        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)) {
435✔
107
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
435✔
108
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
435✔
109
            $configuration['args'] = $args ?: $configuration['args'] ?? $fieldConfiguration['args'] + $extraArgs;
435✔
110

111
            return [$this->inflector->pluralize($fieldName) => array_merge($fieldConfiguration, $configuration)];
435✔
112
        }
113

114
        return [];
×
115
    }
116

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

126
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $description, $operation->getDeprecationReason(), $resourceType, $resourceClass, false, $operation)) {
411✔
127
            $fieldConfiguration['args'] += ['input' => $this->getResourceFieldConfiguration(null, null, $operation->getDeprecationReason(), $resourceType, $resourceClass, true, $operation)];
411✔
128
        }
129

130
        $mutationFields[$operation->getName().$operation->getShortName()] = $fieldConfiguration ?? [];
411✔
131

132
        return $mutationFields;
411✔
133
    }
134

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

144
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $description, $operation->getDeprecationReason(), $resourceType, $resourceClass, false, $operation)) {
408✔
145
            $fieldConfiguration['args'] += ['input' => $this->getResourceFieldConfiguration(null, null, $operation->getDeprecationReason(), $resourceType, $resourceClass, true, $operation)];
408✔
146
        }
147

148
        if (!$fieldConfiguration) {
408✔
149
            return [];
×
150
        }
151

152
        $subscriptionName = $operation->getName();
408✔
153
        // TODO: 3.0 change this
154
        if ('update_subscription' === $subscriptionName) {
408✔
155
            $subscriptionName = 'update';
408✔
156
        }
157

158
        $subscriptionFields[$subscriptionName.$operation->getShortName().'Subscribe'] = $fieldConfiguration;
408✔
159

160
        return $subscriptionFields;
408✔
161
    }
162

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

174
        if (null !== $ioMetadata && \array_key_exists('class', $ioMetadata) && null === $ioMetadata['class']) {
417✔
175
            if ($input) {
12✔
176
                return ['clientMutationId' => $clientMutationId];
9✔
177
            }
178

179
            return [];
9✔
180
        }
181

182
        if ($operation instanceof Subscription && $input) {
414✔
183
            return [
9✔
184
                'id' => $idField,
9✔
185
                'clientSubscriptionId' => $clientSubscriptionId,
9✔
186
            ];
9✔
187
        }
188

189
        if ('delete' === $operation->getName()) {
414✔
190
            $fields = [
14✔
191
                'id' => $idField,
14✔
192
            ];
14✔
193

194
            if ($input) {
14✔
195
                $fields['clientMutationId'] = $clientMutationId;
14✔
196
            }
197

198
            return $fields;
14✔
199
        }
200

201
        if (!$input || (!$operation->getResolver() && 'create' !== $operation->getName())) {
414✔
202
            $fields['id'] = $idField;
408✔
203
        }
204
        if ($input && $depth >= 1) {
414✔
205
            $fields['id'] = $optionalIdField;
12✔
206
        }
207

208
        ++$depth; // increment the depth for the call to getResourceFieldConfiguration.
414✔
209

210
        if (null !== $resourceClass) {
414✔
211
            foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $property) {
414✔
212
                $context = [
414✔
213
                    'normalization_groups' => $operation->getNormalizationContext()['groups'] ?? null,
414✔
214
                    'denormalization_groups' => $operation->getDenormalizationContext()['groups'] ?? null,
414✔
215
                ];
414✔
216
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $property, $context);
414✔
217
                $propertyTypes = $propertyMetadata->getBuiltinTypes();
414✔
218

219
                if (
220
                    !$propertyTypes
414✔
221
                    || (!$input && false === $propertyMetadata->isReadable())
414✔
222
                    || ($input && false === $propertyMetadata->isWritable())
414✔
223
                ) {
224
                    continue;
147✔
225
                }
226

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

238
        if ($operation instanceof Mutation && $input) {
414✔
239
            $fields['clientMutationId'] = $clientMutationId;
114✔
240
        }
241

242
        return $fields;
414✔
243
    }
244

245
    private function isEnumClass(string $resourceClass): bool
246
    {
247
        return is_a($resourceClass, \BackedEnum::class, true);
435✔
248
    }
249

250
    /**
251
     * {@inheritdoc}
252
     */
253
    public function getEnumFields(string $enumClass): array
254
    {
255
        $rEnum = new \ReflectionEnum($enumClass);
16✔
256

257
        $enumCases = [];
16✔
258
        /* @var \ReflectionEnumUnitCase|\ReflectionEnumBackedCase */
259
        foreach ($rEnum->getCases() as $rCase) {
16✔
260
            if ($rCase instanceof \ReflectionEnumBackedCase) {
16✔
261
                $enumCase = ['value' => $rCase->getBackingValue()];
16✔
262
            } else {
263
                $enumCase = ['value' => $rCase->getValue()];
×
264
            }
265

266
            $propertyMetadata = $this->propertyMetadataFactory->create($enumClass, $rCase->getName());
16✔
267
            if ($enumCaseDescription = $propertyMetadata->getDescription()) {
16✔
268
                $enumCase['description'] = $enumCaseDescription;
16✔
269
            }
270
            $enumCases[$rCase->getName()] = $enumCase;
16✔
271
        }
272

273
        return $enumCases;
16✔
274
    }
275

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

286
            $args[$id]['type'] = $this->typeConverter->resolveType($arg['type']);
408✔
287
        }
288

289
        /*
290
         * This is @experimental, read the comment on the parameterToObjectType function as additional information.
291
         */
292
        foreach ($operation->getParameters() ?? [] as $parameter) {
435✔
293
            $key = $parameter->getKey();
411✔
294

295
            if (str_contains($key, ':property')) {
411✔
296
                if (!($filterId = $parameter->getFilter()) || !$this->filterLocator->has($filterId)) {
411✔
297
                    continue;
×
298
                }
299

300
                $parsedKey = explode('[:property]', $key);
411✔
301
                $flattenFields = [];
411✔
302
                foreach ($this->filterLocator->get($filterId)->getDescription($operation->getClass()) as $key => $value) {
411✔
303
                    $values = [];
411✔
304
                    parse_str($key, $values);
411✔
305
                    if (isset($values[$parsedKey[0]])) {
411✔
306
                        $values = $values[$parsedKey[0]];
411✔
307
                    }
308

309
                    $name = key($values);
411✔
310
                    $flattenFields[] = ['name' => $name, 'required' => $value['required'] ?? null, 'description' => $value['description'] ?? null, 'leafs' => $values[$name], 'type' => $value['type'] ?? 'string'];
411✔
311
                }
312

313
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0]);
411✔
314
                continue;
411✔
315
            }
316

317
            $args[$key] = ['type' => GraphQLType::string()];
411✔
318

319
            if ($parameter->getRequired()) {
411✔
320
                $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
321
            }
322
        }
323

324
        return $args;
435✔
325
    }
326

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

342
            if (\is_array($l = $field['leafs'])) {
411✔
343
                if (0 === key($l)) {
411✔
344
                    $key = $key;
411✔
345
                    $type = GraphQLType::listOf($type);
411✔
346
                } else {
347
                    $n = [];
411✔
348
                    foreach ($field['leafs'] as $l => $value) {
411✔
349
                        $n[] = ['required' => null, 'name' => $l, 'leafs' => $value, 'type' => 'string', 'description' => null];
411✔
350
                    }
351

352
                    $type = $this->parameterToObjectType($n, $key);
411✔
353
                    if (isset($fields[$key]) && ($t = $fields[$key]['type']) instanceof InputObjectType) {
411✔
354
                        $t = $fields[$key]['type'];
411✔
355
                        $t->config['fields'] = array_merge($t->config['fields'], $type->config['fields']);
411✔
356
                        $type = $t;
411✔
357
                    }
358
                }
359
            }
360

361
            if ($field['required']) {
411✔
362
                $type = GraphQLType::nonNull($type);
×
363
            }
364

365
            if (isset($fields[$key])) {
411✔
366
                if ($type instanceof ListOfType) {
411✔
367
                    $key .= '_list';
411✔
368
                }
369
            }
370

371
            $fields[$key] = ['type' => $type, 'name' => $key];
411✔
372
        }
373

374
        return new InputObjectType(['name' => $name, 'fields' => $fields]);
411✔
375
    }
376

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

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

404
            if (
405
                $isCollectionType
435✔
406
                && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
435✔
407
            ) {
408
                $resourceClass = $collectionValueType->getClassName();
435✔
409
            } else {
410
                $resourceClass = $type->getClassName();
435✔
411
            }
412

413
            $resourceOperation = $rootOperation;
435✔
414
            if ($resourceClass && $depth >= 1 && $this->resourceClassResolver->isResourceClass($resourceClass)) {
435✔
415
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
279✔
416
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
279✔
417
            }
418

419
            if (!$resourceOperation instanceof Operation) {
435✔
420
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
421
            }
422

423
            $graphqlType = $this->convertType($type, $input, $resourceOperation, $rootOperation, $resourceClass ?? '', $rootResource, $property, $depth, $forceNullable);
435✔
424

425
            $graphqlWrappedType = $graphqlType;
435✔
426
            if ($graphqlType instanceof WrappingType) {
435✔
427
                if (method_exists($graphqlType, 'getInnermostType')) {
435✔
428
                    $graphqlWrappedType = $graphqlType->getInnermostType();
435✔
429
                } else {
430
                    $graphqlWrappedType = $graphqlType->getWrappedType(true);
×
431
                }
432
            }
433
            $isStandardGraphqlType = \in_array($graphqlWrappedType, GraphQLType::getStandardTypes(), true);
435✔
434
            if ($isStandardGraphqlType) {
435✔
435
                $resourceClass = '';
414✔
436
            }
437

438
            // Check mercure attribute if it's a subscription at the root level.
439
            if ($rootOperation instanceof Subscription && null === $property && !$rootOperation->getMercure()) {
435✔
440
                return null;
×
441
            }
442

443
            $args = [];
435✔
444

445
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType && $isCollectionType) {
435✔
446
                if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
435✔
447
                    $args = $this->getGraphQlPaginationArgs($resourceOperation);
414✔
448
                }
449

450
                $args = $this->getFilterArgs($args, $resourceClass, $rootResource, $resourceOperation, $rootOperation, $property, $depth);
435✔
451
            }
452

453
            if ($this->itemResolverFactory instanceof ResolverFactory) {
435✔
454
                if ($isStandardGraphqlType || $input) {
435✔
455
                    $resolve = null;
435✔
456
                } else {
457
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation, $this->propertyMetadataFactory);
435✔
458
                }
459
            } else {
460
                if ($isStandardGraphqlType || $input) {
×
461
                    $resolve = null;
×
462
                } elseif (($rootOperation instanceof Mutation || $rootOperation instanceof Subscription) && $depth <= 0) {
×
463
                    $resolve = $rootOperation instanceof Mutation ? ($this->itemMutationResolverFactory)($resourceClass, $rootResource, $resourceOperation) : ($this->itemSubscriptionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
×
464
                } elseif ($this->typeBuilder->isCollection($type)) {
×
465
                    $resolve = ($this->collectionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
×
466
                } else {
467
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation);
×
468
                }
469
            }
470

471
            return [
435✔
472
                'type' => $graphqlType,
435✔
473
                'description' => $fieldDescription,
435✔
474
                'args' => $args,
435✔
475
                'resolve' => $resolve,
435✔
476
                'deprecationReason' => $deprecationReason,
435✔
477
            ];
435✔
478
        } catch (InvalidTypeException) {
89✔
479
            // just ignore invalid types
480
        }
481

482
        return null;
89✔
483
    }
484

485
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
486
    {
487
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
414✔
488

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

510
        $paginationOptions = $this->pagination->getOptions();
408✔
511

512
        $args = [
408✔
513
            $paginationOptions['page_parameter_name'] => [
408✔
514
                'type' => GraphQLType::int(),
408✔
515
                'description' => 'Returns the current page.',
408✔
516
            ],
408✔
517
        ];
408✔
518

519
        if ($paginationOptions['client_items_per_page']) {
408✔
520
            $args[$paginationOptions['items_per_page_parameter_name']] = [
408✔
521
                'type' => GraphQLType::int(),
408✔
522
                'description' => 'Returns the number of items per page.',
408✔
523
            ];
408✔
524
        }
525

526
        return $args;
408✔
527
    }
528

529
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
530
    {
531
        if (null === $resourceClass) {
435✔
532
            return $args;
×
533
        }
534

535
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
435✔
536
            if (!$this->filterLocator->has($filterId)) {
408✔
537
                continue;
×
538
            }
539

540
            $entityClass = $resourceClass;
408✔
541
            if ($options = $resourceOperation->getStateOptions()) {
408✔
542
                if ($options instanceof Options && $options->getEntityClass()) {
408✔
543
                    $entityClass = $options->getEntityClass();
408✔
544
                }
545

546
                if ($options instanceof ODMOptions && $options->getDocumentClass()) {
408✔
547
                    $entityClass = $options->getDocumentClass();
408✔
548
                }
549
            }
550

551
            foreach ($this->filterLocator->get($filterId)->getDescription($entityClass) as $key => $description) {
408✔
552
                $nullable = isset($description['required']) ? !$description['required'] : true;
408✔
553
                $filterType = \in_array($description['type'], Type::$builtinTypes, true) ? new Type($description['type'], $nullable) : new Type('object', $nullable, $description['type']);
408✔
554
                $graphqlFilterType = $this->convertType($filterType, false, $resourceOperation, $rootOperation, $resourceClass, $rootResource, $property, $depth);
408✔
555

556
                if (str_ends_with($key, '[]')) {
408✔
557
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
408✔
558
                    $key = substr($key, 0, -2).'_list';
408✔
559
                }
560

561
                /** @var string $key */
562
                $key = str_replace('.', $this->nestingSeparator, $key);
408✔
563

564
                parse_str($key, $parsed);
408✔
565
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
408✔
566
                    $parsed = [$key => ''];
×
567
                }
568
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
408✔
569
                    $v = $graphqlFilterType;
408✔
570
                });
408✔
571
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
408✔
572
            }
573
        }
574

575
        return $this->convertFilterArgsToTypes($args);
435✔
576
    }
577

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

586
            if (\is_array($value)) {
408✔
587
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
408✔
588
                if (!isset($value['#name'])) {
408✔
589
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
408✔
590
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
408✔
591
                }
592
            }
593

594
            $args[$key] = $value;
408✔
595
        }
596

597
        return $args;
408✔
598
    }
599

600
    private function convertFilterArgsToTypes(array $args): array
601
    {
602
        foreach ($args as $key => $value) {
435✔
603
            if (strpos($key, '.')) {
414✔
604
                // Declare relations/nested fields in a GraphQL compatible syntax.
605
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
606
                unset($args[$key]);
×
607
            }
608
        }
609

610
        foreach ($args as $key => $value) {
435✔
611
            if (!\is_array($value) || !isset($value['#name'])) {
414✔
612
                continue;
414✔
613
            }
614

615
            $name = $value['#name'];
408✔
616

617
            if ($this->typesContainer->has($name)) {
408✔
618
                $args[$key] = $this->typesContainer->get($name);
26✔
619
                continue;
26✔
620
            }
621

622
            unset($value['#name']);
408✔
623

624
            $filterArgType = GraphQLType::listOf(new InputObjectType([
408✔
625
                'name' => $name,
408✔
626
                'fields' => $this->convertFilterArgsToTypes($value),
408✔
627
            ]));
408✔
628

629
            $this->typesContainer->set($name, $filterArgType);
408✔
630

631
            $args[$key] = $filterArgType;
408✔
632
        }
633

634
        return $args;
435✔
635
    }
636

637
    /**
638
     * Converts a built-in type to its GraphQL equivalent.
639
     *
640
     * @throws InvalidTypeException
641
     */
642
    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
643
    {
644
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
435✔
645

646
        if (null === $graphqlType) {
435✔
647
            throw new InvalidTypeException(sprintf('The type "%s" is not supported.', $type->getBuiltinType()));
89✔
648
        }
649

650
        if (\is_string($graphqlType)) {
435✔
651
            if (!$this->typesContainer->has($graphqlType)) {
311✔
652
                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));
×
653
            }
654

655
            $graphqlType = $this->typesContainer->get($graphqlType);
311✔
656
        }
657

658
        if ($this->typeBuilder->isCollection($type)) {
435✔
659
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
435✔
660
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
414✔
661
            }
662

663
            return GraphQLType::listOf($graphqlType);
432✔
664
        }
665

666
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
435✔
667
            ? $graphqlType
435✔
668
            : GraphQLType::nonNull($graphqlType);
435✔
669
    }
670

671
    private function normalizePropertyName(string $property, string $resourceClass): string
672
    {
673
        if (null === $this->nameConverter) {
408✔
674
            return $property;
×
675
        }
676
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
408✔
677
            return $this->nameConverter->normalize($property, $resourceClass);
408✔
678
        }
679

680
        return $this->nameConverter->normalize($property);
×
681
    }
682
}
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