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

api-platform / core / 18974957045

31 Oct 2025 02:04PM UTC coverage: 24.541% (-0.06%) from 24.603%
18974957045

push

github

web-flow
Merge 4.1 (#7499)

Co-authored-by: Nicolas LAURENT <aegypius@users.noreply.github.com>
Co-authored-by: Javier Sampedro <jsampedro77@gmail.com>
fix(laravel): serializer attributes on Eloquent methods (#7416)
fixes #7289
fixes #7338
fix(validator): custom message was not translated (#7424)
fixes #7336
fix(serializer): resilient denormalizeRelation capability (#7474)
fix(doctrine): properly set properties according to interface (#7487)
fix(graphql): stateOptions to get filter class (#7485)

11 of 232 new or added lines in 20 files covered. (4.74%)

28 existing lines in 6 files now uncovered.

14064 of 57309 relevant lines covered (24.54%)

26.35 hits per line

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

65.68
/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\OpenApiParameterFilterInterface;
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\Metadata\Util\PropertyInfoToTypeInfoHelper;
32
use ApiPlatform\Metadata\Util\TypeHelper;
33
use ApiPlatform\State\Pagination\Pagination;
34
use ApiPlatform\State\Util\StateOptionsTrait;
35
use GraphQL\Type\Definition\InputObjectType;
36
use GraphQL\Type\Definition\ListOfType;
37
use GraphQL\Type\Definition\NonNull;
38
use GraphQL\Type\Definition\NullableType;
39
use GraphQL\Type\Definition\Type as GraphQLType;
40
use GraphQL\Type\Definition\WrappingType;
41
use Psr\Container\ContainerInterface;
42
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
43
use Symfony\Component\PropertyInfo\Type as LegacyType;
44
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
45
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
46
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
47
use Symfony\Component\TypeInfo\Type;
48
use Symfony\Component\TypeInfo\Type\CollectionType;
49
use Symfony\Component\TypeInfo\Type\ObjectType;
50
use Symfony\Component\TypeInfo\TypeIdentifier;
51

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

61
    private readonly ContextAwareTypeBuilderInterface $typeBuilder;
62

63
    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())
64
    {
65
        $this->typeBuilder = $typeBuilder;
26✔
66
    }
67

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

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

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

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

98
            return [$fieldName => array_merge($fieldConfiguration, $configuration)];
24✔
99
        }
100

101
        return [];
×
102
    }
103

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

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

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

120
            return [$this->inflector->pluralize($fieldName) => array_merge($fieldConfiguration, $configuration)];
26✔
121
        }
122

123
        return [];
×
124
    }
125

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

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

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

141
        return $mutationFields;
10✔
142
    }
143

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

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

157
        if (!$fieldConfiguration) {
×
158
            return [];
×
159
        }
160

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

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

169
        return $subscriptionFields;
×
170
    }
171

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

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

188
            return [];
×
189
        }
190

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

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

203
            if ($input) {
×
204
                $fields['clientMutationId'] = $clientMutationId;
×
205
            }
206

207
            return $fields;
×
208
        }
209

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

217
        ++$depth; // increment the depth for the call to getResourceFieldConfiguration.
26✔
218

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

227
                if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
26✔
228
                    $propertyTypes = $propertyMetadata->getBuiltinTypes();
×
229

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

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

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

262
        if ($operation instanceof Mutation && $input) {
26✔
263
            $fields['clientMutationId'] = $clientMutationId;
2✔
264
        }
265

266
        return $fields;
26✔
267
    }
268

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

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

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

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

297
        return $enumCases;
2✔
298
    }
299

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

310
            $args[$id]['type'] = $this->typeConverter->resolveType($arg['type']);
×
311
        }
312

313
        return $args;
26✔
314
    }
315

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

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

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

354
            if ($field['required']) {
2✔
355
                $type = GraphQLType::nonNull($type);
×
356
            }
357

358
            if (isset($fields[$key])) {
2✔
359
                if ($type instanceof ListOfType) {
2✔
360
                    $key .= '_list';
2✔
361
                }
362
            }
363

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

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

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

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

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

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

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

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

398
    /**
399
     * Get the field configuration of a resource.
400
     *
401
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
402
     */
403
    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
404
    {
405
        if ($type instanceof LegacyType) {
26✔
406
            $type = PropertyInfoToTypeInfoHelper::convertLegacyTypesToType([$type]);
×
407
        }
408

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

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

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

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

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

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

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

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

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

455
            $args = [];
26✔
456

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

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

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

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

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

493
        return null;
2✔
494
    }
495

496
    /*
497
     * This function is @experimental, read the comment on the parameterToObjectType function for additional information.
498
     * @experimental
499
     */
500
    private function getParameterArgs(Operation $operation, array $args = []): array
501
    {
502
        foreach ($operation->getParameters() ?? [] as $parameter) {
26✔
503
            $key = $parameter->getKey();
2✔
504

505
            if (!str_contains($key, ':property')) {
2✔
506
                $args[$key] = ['type' => GraphQLType::string()];
2✔
507

508
                if ($parameter->getRequired()) {
2✔
509
                    $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
510
                }
511

512
                continue;
2✔
513
            }
514

515
            if (!($filterId = $parameter->getFilter()) || !$this->filterLocator->has($filterId)) {
2✔
516
                continue;
×
517
            }
518

519
            $filter = $this->filterLocator->get($filterId);
2✔
520
            $parsedKey = explode('[:property]', $key);
2✔
521
            $flattenFields = [];
2✔
522

523
            if ($filter instanceof FilterInterface) {
2✔
524
                foreach ($filter->getDescription($operation->getClass()) as $name => $value) {
2✔
525
                    $values = [];
2✔
526
                    parse_str($name, $values);
2✔
527
                    if (isset($values[$parsedKey[0]])) {
2✔
528
                        $values = $values[$parsedKey[0]];
2✔
529
                    }
530

531
                    $name = key($values);
2✔
532
                    $flattenFields[] = ['name' => $name, 'required' => $value['required'] ?? null, 'description' => $value['description'] ?? null, 'leafs' => $values[$name], 'type' => $value['type'] ?? 'string'];
2✔
533
                }
534

535
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0]);
2✔
536
            }
537

538
            if ($filter instanceof OpenApiParameterFilterInterface) {
2✔
539
                foreach ($filter->getOpenApiParameters($parameter) as $value) {
2✔
540
                    $values = [];
2✔
541
                    parse_str($value->getName(), $values);
2✔
542
                    if (isset($values[$parsedKey[0]])) {
2✔
543
                        $values = $values[$parsedKey[0]];
2✔
544
                    }
545

546
                    $name = key($values);
2✔
547
                    $flattenFields[] = ['name' => $name, 'required' => $value->getRequired(), 'description' => $value->getDescription(), 'leafs' => $values[$name], 'type' => $value->getSchema()['type'] ?? 'string'];
2✔
548
                }
549

550
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0].$operation->getShortName().$operation->getName());
2✔
551
            }
552
        }
553

554
        return $args;
26✔
555
    }
556

557
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
558
    {
559
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
12✔
560

561
        if ('cursor' === $paginationType) {
12✔
562
            return [
12✔
563
                'first' => [
12✔
564
                    'type' => GraphQLType::int(),
12✔
565
                    'description' => 'Returns the first n elements from the list.',
12✔
566
                ],
12✔
567
                'last' => [
12✔
568
                    'type' => GraphQLType::int(),
12✔
569
                    'description' => 'Returns the last n elements from the list.',
12✔
570
                ],
12✔
571
                'before' => [
12✔
572
                    'type' => GraphQLType::string(),
12✔
573
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
12✔
574
                ],
12✔
575
                'after' => [
12✔
576
                    'type' => GraphQLType::string(),
12✔
577
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
12✔
578
                ],
12✔
579
            ];
12✔
580
        }
581

582
        $paginationOptions = $this->pagination->getOptions();
×
583

584
        $args = [
×
585
            $paginationOptions['page_parameter_name'] => [
×
586
                'type' => GraphQLType::int(),
×
587
                'description' => 'Returns the current page.',
×
588
            ],
×
589
        ];
×
590

591
        if ($paginationOptions['client_items_per_page']) {
×
592
            $args[$paginationOptions['items_per_page_parameter_name']] = [
×
593
                'type' => GraphQLType::int(),
×
594
                'description' => 'Returns the number of items per page.',
×
595
            ];
×
596
        }
597

598
        return $args;
×
599
    }
600

601
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
602
    {
603
        if (null === $resourceClass) {
26✔
604
            return $args;
×
605
        }
606

607
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
26✔
608
            if (!$this->filterLocator->has($filterId)) {
×
609
                continue;
×
610
            }
611

NEW
612
            $entityClass = $this->getStateOptionsClass($resourceOperation, $resourceOperation->getClass());
×
NEW
613
            foreach ($this->filterLocator->get($filterId)->getDescription($entityClass) as $key => $description) {
×
614
                $filterType = \in_array($description['type'], TypeIdentifier::values(), true) ? Type::builtin($description['type']) : Type::object($description['type']);
×
615
                if (!($description['required'] ?? false)) {
×
616
                    $filterType = Type::nullable($filterType);
×
617
                }
618
                $graphqlFilterType = $this->convertType($filterType, false, $resourceOperation, $rootOperation, $resourceClass, $rootResource, $property, $depth);
×
619

620
                if (str_ends_with($key, '[]')) {
×
621
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
×
622
                    $key = substr($key, 0, -2).'_list';
×
623
                }
624

625
                /** @var string $key */
626
                $key = str_replace('.', $this->nestingSeparator, $key);
×
627

628
                parse_str($key, $parsed);
×
629
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
×
630
                    $parsed = [$key => ''];
×
631
                }
632
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
×
633
                    $v = $graphqlFilterType;
×
634
                });
×
635
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
×
636
            }
637
        }
638

639
        return $this->convertFilterArgsToTypes($args);
26✔
640
    }
641

642
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
643
    {
644
        foreach ($parsed as $key => $value) {
×
645
            // Never override keys that cannot be merged
646
            if (isset($args[$key]) && !\is_array($args[$key])) {
×
647
                continue;
×
648
            }
649

650
            if (\is_array($value)) {
×
651
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
×
652
                if (!isset($value['#name'])) {
×
653
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
×
654
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
×
655
                }
656
            }
657

658
            $args[$key] = $value;
×
659
        }
660

661
        return $args;
×
662
    }
663

664
    private function convertFilterArgsToTypes(array $args): array
665
    {
666
        foreach ($args as $key => $value) {
26✔
667
            if (strpos($key, '.')) {
12✔
668
                // Declare relations/nested fields in a GraphQL compatible syntax.
669
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
670
                unset($args[$key]);
×
671
            }
672
        }
673

674
        foreach ($args as $key => $value) {
26✔
675
            if (!\is_array($value) || !isset($value['#name'])) {
12✔
676
                continue;
12✔
677
            }
678

679
            $name = $value['#name'];
×
680

681
            if ($this->typesContainer->has($name)) {
×
682
                $args[$key] = $this->typesContainer->get($name);
×
683
                continue;
×
684
            }
685

686
            unset($value['#name']);
×
687

688
            $filterArgType = GraphQLType::listOf(new InputObjectType([
×
689
                'name' => $name,
×
690
                'fields' => $this->convertFilterArgsToTypes($value),
×
691
            ]));
×
692

693
            $this->typesContainer->set($name, $filterArgType);
×
694

695
            $args[$key] = $filterArgType;
×
696
        }
697

698
        return $args;
26✔
699
    }
700

701
    /**
702
     * Converts a built-in type to its GraphQL equivalent.
703
     *
704
     * @throws InvalidTypeException
705
     */
706
    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
707
    {
708
        if ($type instanceof LegacyType) {
26✔
709
            $type = PropertyInfoToTypeInfoHelper::convertLegacyTypesToType([$type]);
×
710
        }
711

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

714
        if (null === $graphqlType) {
26✔
715
            throw new InvalidTypeException(\sprintf('The type "%s" is not supported.', (string) $type));
2✔
716
        }
717

718
        if (\is_string($graphqlType)) {
26✔
719
            if (!$this->typesContainer->has($graphqlType)) {
×
720
                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));
×
721
            }
722

723
            $graphqlType = $this->typesContainer->get($graphqlType);
×
724
        }
725

726
        if ($type->isSatisfiedBy(fn ($t) => $t instanceof CollectionType) && ($collectionValueType = TypeHelper::getCollectionValueType($type)) && TypeHelper::getClassName($collectionValueType)) {
26✔
727
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
26✔
728
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
12✔
729
            }
730

731
            return GraphQLType::listOf($graphqlType);
18✔
732
        }
733

734
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
26✔
735
            ? $graphqlType
26✔
736
            : GraphQLType::nonNull($graphqlType);
26✔
737
    }
738

739
    private function normalizePropertyName(string $property, string $resourceClass): string
740
    {
741
        if (null === $this->nameConverter) {
26✔
742
            return $property;
×
743
        }
744
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
26✔
745
            return $this->nameConverter->normalize($property, $resourceClass);
26✔
746
        }
747

748
        return $this->nameConverter->normalize($property);
×
749
    }
750
}
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