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

api-platform / core / 20001323174

07 Dec 2025 08:10AM UTC coverage: 25.292% (+0.001%) from 25.291%
20001323174

push

github

soyuka
chore: bump metadata to 4.3.x-dev

14642 of 57891 relevant lines covered (25.29%)

28.94 hits per line

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

65.13
/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\GraphQl\Exception\InvalidTypeException;
17
use ApiPlatform\GraphQl\Resolver\Factory\ResolverFactoryInterface;
18
use ApiPlatform\GraphQl\Type\Definition\TypeInterface;
19
use ApiPlatform\Metadata\FilterInterface;
20
use ApiPlatform\Metadata\GraphQl\Mutation;
21
use ApiPlatform\Metadata\GraphQl\Operation;
22
use ApiPlatform\Metadata\GraphQl\Query;
23
use ApiPlatform\Metadata\GraphQl\Subscription;
24
use ApiPlatform\Metadata\InflectorInterface;
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\Metadata\Util\PropertyInfoToTypeInfoHelper;
31
use ApiPlatform\Metadata\Util\TypeHelper;
32
use ApiPlatform\State\Pagination\Pagination;
33
use ApiPlatform\State\Util\StateOptionsTrait;
34
use GraphQL\Type\Definition\InputObjectType;
35
use GraphQL\Type\Definition\ListOfType;
36
use GraphQL\Type\Definition\NonNull;
37
use GraphQL\Type\Definition\NullableType;
38
use GraphQL\Type\Definition\Type as GraphQLType;
39
use GraphQL\Type\Definition\WrappingType;
40
use Psr\Container\ContainerInterface;
41
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
42
use Symfony\Component\PropertyInfo\Type as LegacyType;
43
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
44
use Symfony\Component\TypeInfo\Type;
45
use Symfony\Component\TypeInfo\Type\CollectionType;
46
use Symfony\Component\TypeInfo\Type\ObjectType;
47
use Symfony\Component\TypeInfo\TypeIdentifier;
48

49
/**
50
 * Builds the GraphQL fields.
51
 *
52
 * @author Alan Poulain <contact@alanpoulain.eu>
53
 */
54
final class FieldsBuilder implements FieldsBuilderEnumInterface
55
{
56
    use StateOptionsTrait;
57

58
    private readonly ContextAwareTypeBuilderInterface $typeBuilder;
59

60
    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 $resolverFactory, private readonly ContainerInterface $filterLocator, private readonly Pagination $pagination, private readonly ?NameConverterInterface $nameConverter, private readonly string $nestingSeparator, private readonly ?InflectorInterface $inflector = new Inflector())
61
    {
62
        $this->typeBuilder = $typeBuilder;
26✔
63
    }
64

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

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

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

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

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

98
        return [];
×
99
    }
100

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

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

112
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), Type::collection(Type::object(\stdClass::class), Type::object($resourceClass)), $resourceClass, false, $operation)) {
26✔
113
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
26✔
114
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
26✔
115
            $configuration['args'] = $args ?: $configuration['args'] ?? $fieldConfiguration['args'] + $extraArgs;
26✔
116

117
            return [$this->inflector->pluralize($fieldName) => array_merge($fieldConfiguration, $configuration)];
26✔
118
        }
119

120
        return [];
×
121
    }
122

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

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

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

138
        return $mutationFields;
10✔
139
    }
140

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

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

154
        if (!$fieldConfiguration) {
×
155
            return [];
×
156
        }
157

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

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

166
        return $subscriptionFields;
×
167
    }
168

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

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

185
            return [];
×
186
        }
187

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

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

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

204
            return $fields;
×
205
        }
206

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

214
        ++$depth; // increment the depth for the call to getResourceFieldConfiguration.
26✔
215

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

224
                if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
26✔
225
                    $propertyTypes = $propertyMetadata->getBuiltinTypes();
×
226

227
                    if (
228
                        !$propertyTypes
×
229
                        || (!$input && false === $propertyMetadata->isReadable())
×
230
                        || ($input && false === $propertyMetadata->isWritable())
×
231
                    ) {
232
                        continue;
×
233
                    }
234

235
                    // guess union/intersect types: check each type until finding a valid one
236
                    foreach ($propertyTypes as $propertyType) {
×
237
                        if ($fieldConfiguration = $this->getResourceFieldConfiguration($property, $propertyMetadata->getDescription(), $propertyMetadata->getDeprecationReason(), $propertyType, $resourceClass, $input, $operation, $depth, null !== $propertyMetadata->getSecurity())) {
×
238
                            $fields['id' === $property ? '_id' : $this->normalizePropertyName($property, $resourceClass)] = $fieldConfiguration;
×
239
                            // stop at the first valid type
240
                            break;
×
241
                        }
242
                    }
243
                } else {
244
                    if (
245
                        !($propertyType = $propertyMetadata->getNativeType())
26✔
246
                        || (!$input && false === $propertyMetadata->isReadable())
26✔
247
                        || ($input && false === $propertyMetadata->isWritable())
26✔
248
                    ) {
249
                        continue;
14✔
250
                    }
251

252
                    if ($fieldConfiguration = $this->getResourceFieldConfiguration($property, $propertyMetadata->getDescription(), $propertyMetadata->getDeprecationReason(), $propertyType, $resourceClass, $input, $operation, $depth, null !== $propertyMetadata->getSecurity())) {
26✔
253
                        $fields['id' === $property ? '_id' : $this->normalizePropertyName($property, $resourceClass)] = $fieldConfiguration;
26✔
254
                    }
255
                }
256
            }
257
        }
258

259
        if ($operation instanceof Mutation && $input) {
26✔
260
            $fields['clientMutationId'] = $clientMutationId;
2✔
261
        }
262

263
        return $fields;
26✔
264
    }
265

266
    private function isEnumClass(string $resourceClass): bool
267
    {
268
        return is_a($resourceClass, \BackedEnum::class, true);
26✔
269
    }
270

271
    /**
272
     * {@inheritdoc}
273
     */
274
    public function getEnumFields(string $enumClass): array
275
    {
276
        $rEnum = new \ReflectionEnum($enumClass);
2✔
277

278
        $enumCases = [];
2✔
279
        /* @var \ReflectionEnumUnitCase|\ReflectionEnumBackedCase */
280
        foreach ($rEnum->getCases() as $rCase) {
2✔
281
            if ($rCase instanceof \ReflectionEnumBackedCase) {
2✔
282
                $enumCase = ['value' => $rCase->getBackingValue()];
2✔
283
            } else {
284
                $enumCase = ['value' => $rCase->getValue()];
×
285
            }
286

287
            $propertyMetadata = $this->propertyMetadataFactory->create($enumClass, $rCase->getName());
2✔
288
            if ($enumCaseDescription = $propertyMetadata->getDescription()) {
2✔
289
                $enumCase['description'] = $enumCaseDescription;
2✔
290
            }
291
            $enumCases[$rCase->getName()] = $enumCase;
2✔
292
        }
293

294
        return $enumCases;
2✔
295
    }
296

297
    /**
298
     * {@inheritdoc}
299
     */
300
    public function resolveResourceArgs(array $args, Operation $operation): array
301
    {
302
        foreach ($args as $id => $arg) {
26✔
303
            if (!isset($arg['type'])) {
×
304
                throw new \InvalidArgumentException(\sprintf('The argument "%s" of the custom operation "%s" in %s needs a "type" option.', $id, $operation->getName(), $operation->getShortName()));
×
305
            }
306

307
            $args[$id]['type'] = $this->typeConverter->resolveType($arg['type']);
×
308
        }
309

310
        return $args;
26✔
311
    }
312

313
    /**
314
     * Transform the result of a parse_str to a GraphQL object type.
315
     * We should consider merging getFilterArgs and this, `getFilterArgs` uses `convertType` whereas we assume that parameters have only scalar types.
316
     * Note that this method has a lower complexity then the `getFilterArgs` one.
317
     * TODO: Is there a use case with an argument being a complex type (eg: a Resource, Enum etc.)?
318
     *
319
     * @param array<array{name: string, required: bool|null, description: string|null, leafs: string|array, type: string}> $flattenFields
320
     */
321
    private function parameterToObjectType(array $flattenFields, string $name): InputObjectType
322
    {
323
        $fields = [];
2✔
324
        foreach ($flattenFields as $field) {
2✔
325
            $key = $field['name'];
2✔
326
            $type = \in_array($field['type'], TypeIdentifier::values(), true) ? Type::builtin($field['type']) : Type::object($field['type']);
2✔
327
            if (!$field['required']) {
2✔
328
                $type = Type::nullable($type);
2✔
329
            }
330

331
            $type = $this->getParameterType($type);
2✔
332
            if (\is_array($l = $field['leafs'])) {
2✔
333
                if (0 === key($l)) {
2✔
334
                    $key = $key;
2✔
335
                    $type = GraphQLType::listOf($type);
2✔
336
                } else {
337
                    $n = [];
2✔
338
                    foreach ($field['leafs'] as $l => $value) {
2✔
339
                        $n[] = ['required' => null, 'name' => $l, 'leafs' => $value, 'type' => 'string', 'description' => null];
2✔
340
                    }
341

342
                    $type = $this->parameterToObjectType($n, $key);
2✔
343
                    if (isset($fields[$key]) && ($t = $fields[$key]['type']) instanceof InputObjectType) {
2✔
344
                        $t = $fields[$key]['type'];
×
345
                        $t->config['fields'] = array_merge($t->config['fields'], $type->config['fields']);
×
346
                        $type = $t;
×
347
                    }
348
                }
349
            }
350

351
            if ($field['required']) {
2✔
352
                $type = GraphQLType::nonNull($type);
×
353
            }
354

355
            if (isset($fields[$key])) {
2✔
356
                if ($type instanceof ListOfType) {
×
357
                    $key .= '_list';
×
358
                } elseif ($fields[$key]['type'] instanceof InputObjectType && !$type instanceof InputObjectType) {
×
359
                    continue;
×
360
                }
361
            }
362

363
            $fields[$key] = ['type' => $type, 'name' => $key];
2✔
364
        }
365

366
        return new InputObjectType(['name' => $name, 'fields' => $fields]);
2✔
367
    }
368

369
    /**
370
     * A simplified version of convert type that does not support resources.
371
     */
372
    private function getParameterType(Type $type): GraphQLType
373
    {
374
        if ($type->isIdentifiedBy(TypeIdentifier::BOOL)) {
2✔
375
            return GraphQLType::boolean();
×
376
        }
377

378
        if ($type->isIdentifiedBy(TypeIdentifier::INT)) {
2✔
379
            return GraphQLType::int();
×
380
        }
381

382
        if ($type->isIdentifiedBy(TypeIdentifier::FLOAT)) {
2✔
383
            return GraphQLType::float();
×
384
        }
385

386
        if ($type->isIdentifiedBy(TypeIdentifier::STRING, TypeIdentifier::OBJECT)) {
2✔
387
            return GraphQLType::string();
2✔
388
        }
389

390
        if ($type instanceof CollectionType) {
×
391
            return GraphQLType::listOf($this->getParameterType($type->getCollectionValueType()));
×
392
        }
393

394
        return GraphQLType::string();
×
395
    }
396

397
    /**
398
     * Get the field configuration of a resource.
399
     *
400
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
401
     */
402
    private function getResourceFieldConfiguration(?string $property, ?string $fieldDescription, ?string $deprecationReason, Type|LegacyType $type, string $rootResource, bool $input, Operation $rootOperation, int $depth = 0, bool $forceNullable = false): ?array
403
    {
404
        if ($type instanceof LegacyType) {
26✔
405
            $type = PropertyInfoToTypeInfoHelper::convertLegacyTypesToType([$type]);
×
406
        }
407

408
        try {
409
            $isCollectionType = $type->isSatisfiedBy(fn ($t) => $t instanceof CollectionType) && ($v = TypeHelper::getCollectionValueType($type)) && TypeHelper::getClassName($v);
26✔
410

411
            $valueType = $type;
26✔
412
            if ($isCollectionType) {
26✔
413
                $valueType = TypeHelper::getCollectionValueType($type);
26✔
414
            }
415

416
            /** @var class-string|null $resourceClass */
417
            $resourceClass = null;
26✔
418
            $typeIsResourceClass = function (Type $type) use (&$resourceClass): bool {
26✔
419
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($resourceClass = $type->getClassName());
26✔
420
            };
26✔
421

422
            $isResourceClass = $valueType->isSatisfiedBy($typeIsResourceClass);
26✔
423

424
            $resourceOperation = $rootOperation;
26✔
425
            if ($resourceClass && $depth >= 1 && $isResourceClass) {
26✔
426
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
2✔
427
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
2✔
428
            }
429

430
            if (!$resourceOperation instanceof Operation) {
26✔
431
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
432
            }
433

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

436
            $graphqlWrappedType = $graphqlType;
26✔
437
            if ($graphqlType instanceof WrappingType) {
26✔
438
                if (method_exists($graphqlType, 'getInnermostType')) {
26✔
439
                    $graphqlWrappedType = $graphqlType->getInnermostType();
26✔
440
                } else {
441
                    $graphqlWrappedType = $graphqlType->getWrappedType(true);
×
442
                }
443
            }
444
            $isStandardGraphqlType = \in_array($graphqlWrappedType, GraphQLType::getStandardTypes(), true);
26✔
445
            if ($isStandardGraphqlType) {
26✔
446
                $resourceClass = '';
26✔
447
            }
448

449
            // Check mercure attribute if it's a subscription at the root level.
450
            if ($rootOperation instanceof Subscription && null === $property && !$rootOperation->getMercure()) {
26✔
451
                return null;
×
452
            }
453

454
            $args = [];
26✔
455

456
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType) {
26✔
457
                if ($isCollectionType) {
26✔
458
                    if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
26✔
459
                        $args = $this->getGraphQlPaginationArgs($resourceOperation);
12✔
460
                    }
461

462
                    $args = $this->getFilterArgs($args, $resourceClass, $rootResource, $resourceOperation, $rootOperation, $property, $depth);
26✔
463

464
                    // Also register parameter args in the types container
465
                    // Note: This is a workaround, for more information read the comment on the parameterToObjectType function.
466
                    foreach ($this->getParameterArgs($rootOperation) as $key => $arg) {
26✔
467
                        if ($arg instanceof InputObjectType || (\is_array($arg) && isset($arg['name']))) {
2✔
468
                            $this->typesContainer->set(\is_array($arg) ? $arg['name'] : $arg->name(), $arg);
2✔
469
                        }
470
                        $args[$key] = $arg;
2✔
471
                    }
472
                }
473
            }
474

475
            if ($isStandardGraphqlType || $input) {
26✔
476
                $resolve = null;
26✔
477
            } else {
478
                $resolve = ($this->resolverFactory)($resourceClass, $rootResource, $resourceOperation, $this->propertyMetadataFactory);
26✔
479
            }
480

481
            return [
26✔
482
                'type' => $graphqlType,
26✔
483
                'description' => $fieldDescription,
26✔
484
                'args' => $args,
26✔
485
                'resolve' => $resolve,
26✔
486
                'deprecationReason' => $deprecationReason,
26✔
487
            ];
26✔
488
        } catch (InvalidTypeException) {
2✔
489
            // just ignore invalid types
490
        }
491

492
        return null;
2✔
493
    }
494

495
    /*
496
     * This function is @experimental, read the comment on the parameterToObjectType function for additional information.
497
     * @experimental
498
     */
499
    private function getParameterArgs(Operation $operation, array $args = []): array
500
    {
501
        $groups = [];
26✔
502

503
        foreach ($operation->getParameters() ?? [] as $parameter) {
26✔
504
            $key = $parameter->getKey();
2✔
505

506
            if (str_contains($key, '[')) {
2✔
507
                $key = str_replace('.', $this->nestingSeparator, $key);
2✔
508
                parse_str($key, $values);
2✔
509
                $rootKey = key($values);
2✔
510

511
                $leafs = $values[$rootKey];
2✔
512
                $name = key($leafs);
2✔
513

514
                $filterLeafs = [];
2✔
515
                if (($filterId = $parameter->getFilter()) && $this->filterLocator->has($filterId)) {
2✔
516
                    $filter = $this->filterLocator->get($filterId);
2✔
517

518
                    if ($filter instanceof FilterInterface) {
2✔
519
                        $property = $parameter->getProperty() ?? $name;
2✔
520
                        $property = str_replace('.', $this->nestingSeparator, $property);
2✔
521
                        $description = $filter->getDescription($operation->getClass());
2✔
522

523
                        foreach ($description as $descKey => $descValue) {
2✔
524
                            $descKey = str_replace('.', $this->nestingSeparator, $descKey);
2✔
525
                            parse_str($descKey, $descValues);
2✔
526
                            if (isset($descValues[$property]) && \is_array($descValues[$property])) {
2✔
527
                                $filterLeafs = array_merge($filterLeafs, $descValues[$property]);
2✔
528
                            }
529
                        }
530
                    }
531
                }
532

533
                if ($filterLeafs) {
2✔
534
                    $leafs[$name] = $filterLeafs;
2✔
535
                }
536

537
                $groups[$rootKey][] = [
2✔
538
                    'name' => $name,
2✔
539
                    'leafs' => $leafs[$name],
2✔
540
                    'required' => $parameter->getRequired(),
2✔
541
                    'description' => $parameter->getDescription(),
2✔
542
                    'type' => 'string',
2✔
543
                ];
2✔
544
                continue;
2✔
545
            }
546

547
            $args[$key] = ['type' => GraphQLType::string()];
2✔
548

549
            if ($parameter->getRequired()) {
2✔
550
                $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
551
            }
552
        }
553

554
        foreach ($groups as $key => $flattenFields) {
26✔
555
            $name = $key.$operation->getShortName().$operation->getName();
2✔
556
            $inputObject = $this->parameterToObjectType($flattenFields, $name);
2✔
557
            $this->typesContainer->set($name, $inputObject);
2✔
558
            $args[$key] = $inputObject;
2✔
559
        }
560

561
        return $args;
26✔
562
    }
563

564
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
565
    {
566
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
12✔
567

568
        if ('cursor' === $paginationType) {
12✔
569
            return [
12✔
570
                'first' => [
12✔
571
                    'type' => GraphQLType::int(),
12✔
572
                    'description' => 'Returns the first n elements from the list.',
12✔
573
                ],
12✔
574
                'last' => [
12✔
575
                    'type' => GraphQLType::int(),
12✔
576
                    'description' => 'Returns the last n elements from the list.',
12✔
577
                ],
12✔
578
                'before' => [
12✔
579
                    'type' => GraphQLType::string(),
12✔
580
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
12✔
581
                ],
12✔
582
                'after' => [
12✔
583
                    'type' => GraphQLType::string(),
12✔
584
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
12✔
585
                ],
12✔
586
            ];
12✔
587
        }
588

589
        $paginationOptions = $this->pagination->getOptions();
×
590

591
        $args = [
×
592
            $paginationOptions['page_parameter_name'] => [
×
593
                'type' => GraphQLType::int(),
×
594
                'description' => 'Returns the current page.',
×
595
            ],
×
596
        ];
×
597

598
        if ($paginationOptions['client_items_per_page']) {
×
599
            $args[$paginationOptions['items_per_page_parameter_name']] = [
×
600
                'type' => GraphQLType::int(),
×
601
                'description' => 'Returns the number of items per page.',
×
602
            ];
×
603
        }
604

605
        return $args;
×
606
    }
607

608
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
609
    {
610
        if (null === $resourceClass) {
26✔
611
            return $args;
×
612
        }
613

614
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
26✔
615
            if (!$this->filterLocator->has($filterId)) {
×
616
                continue;
×
617
            }
618

619
            $entityClass = $this->getStateOptionsClass($resourceOperation, $resourceOperation->getClass());
×
620
            foreach ($this->filterLocator->get($filterId)->getDescription($entityClass) as $key => $description) {
×
621
                $filterType = \in_array($description['type'], TypeIdentifier::values(), true) ? Type::builtin($description['type']) : Type::object($description['type']);
×
622
                if (!($description['required'] ?? false)) {
×
623
                    $filterType = Type::nullable($filterType);
×
624
                }
625
                $graphqlFilterType = $this->convertType($filterType, false, $resourceOperation, $rootOperation, $resourceClass, $rootResource, $property, $depth);
×
626

627
                if (str_ends_with($key, '[]')) {
×
628
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
×
629
                    $key = substr($key, 0, -2).'_list';
×
630
                }
631

632
                /** @var string $key */
633
                $key = str_replace('.', $this->nestingSeparator, $key);
×
634

635
                parse_str($key, $parsed);
×
636
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
×
637
                    $parsed = [$key => ''];
×
638
                }
639
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
×
640
                    $v = $graphqlFilterType;
×
641
                });
×
642
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
×
643
            }
644
        }
645

646
        return $this->convertFilterArgsToTypes($args);
26✔
647
    }
648

649
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
650
    {
651
        foreach ($parsed as $key => $value) {
×
652
            // Never override keys that cannot be merged
653
            if (isset($args[$key]) && !\is_array($args[$key])) {
×
654
                continue;
×
655
            }
656

657
            if (\is_array($value)) {
×
658
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
×
659
                if (!isset($value['#name'])) {
×
660
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
×
661
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
×
662
                }
663
            }
664

665
            $args[$key] = $value;
×
666
        }
667

668
        return $args;
×
669
    }
670

671
    private function convertFilterArgsToTypes(array $args): array
672
    {
673
        foreach ($args as $key => $value) {
26✔
674
            if (strpos($key, '.')) {
12✔
675
                // Declare relations/nested fields in a GraphQL compatible syntax.
676
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
677
                unset($args[$key]);
×
678
            }
679
        }
680

681
        foreach ($args as $key => $value) {
26✔
682
            if (!\is_array($value) || !isset($value['#name'])) {
12✔
683
                continue;
12✔
684
            }
685

686
            $name = $value['#name'];
×
687

688
            if ($this->typesContainer->has($name)) {
×
689
                $args[$key] = $this->typesContainer->get($name);
×
690
                continue;
×
691
            }
692

693
            unset($value['#name']);
×
694

695
            $filterArgType = GraphQLType::listOf(new InputObjectType([
×
696
                'name' => $name,
×
697
                'fields' => $this->convertFilterArgsToTypes($value),
×
698
            ]));
×
699

700
            $this->typesContainer->set($name, $filterArgType);
×
701

702
            $args[$key] = $filterArgType;
×
703
        }
704

705
        return $args;
26✔
706
    }
707

708
    /**
709
     * Converts a built-in type to its GraphQL equivalent.
710
     *
711
     * @throws InvalidTypeException
712
     */
713
    private function convertType(Type|LegacyType $type, bool $input, Operation $resourceOperation, Operation $rootOperation, string $resourceClass, string $rootResource, ?string $property, int $depth, bool $forceNullable = false): GraphQLType|ListOfType|NonNull
714
    {
715
        if ($type instanceof LegacyType) {
26✔
716
            $type = PropertyInfoToTypeInfoHelper::convertLegacyTypesToType([$type]);
×
717
        }
718

719
        $graphqlType = $this->typeConverter->convertPhpType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
26✔
720

721
        if (null === $graphqlType) {
26✔
722
            throw new InvalidTypeException(\sprintf('The type "%s" is not supported.', (string) $type));
2✔
723
        }
724

725
        if (\is_string($graphqlType)) {
26✔
726
            if (!$this->typesContainer->has($graphqlType)) {
×
727
                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));
×
728
            }
729

730
            $graphqlType = $this->typesContainer->get($graphqlType);
×
731
        }
732

733
        if ($type->isSatisfiedBy(fn ($t) => $t instanceof CollectionType) && ($collectionValueType = TypeHelper::getCollectionValueType($type)) && TypeHelper::getClassName($collectionValueType)) {
26✔
734
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
26✔
735
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
12✔
736
            }
737

738
            return GraphQLType::listOf($graphqlType);
18✔
739
        }
740

741
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
26✔
742
            ? $graphqlType
26✔
743
            : GraphQLType::nonNull($graphqlType);
26✔
744
    }
745

746
    private function normalizePropertyName(string $property, string $resourceClass): string
747
    {
748
        if (null === $this->nameConverter) {
26✔
749
            return $property;
×
750
        }
751

752
        return $this->nameConverter->normalize($property, $resourceClass);
26✔
753
    }
754
}
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