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

api-platform / core / 11555809379

28 Oct 2024 02:12PM UTC coverage: 62.1%. Remained the same
11555809379

push

github

web-flow
chore(symfony): conflict with symfony/framework-bundle 7.1.6 (#6759)

11450 of 18438 relevant lines covered (62.1%)

67.93 hits per line

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

86.77
/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\Exception\InvalidTypeException;
19
use ApiPlatform\GraphQl\Resolver\Factory\ResolverFactory;
20
use ApiPlatform\GraphQl\Resolver\Factory\ResolverFactoryInterface;
21
use ApiPlatform\GraphQl\Type\Definition\TypeInterface;
22
use ApiPlatform\Metadata\FilterInterface;
23
use ApiPlatform\Metadata\GraphQl\Mutation;
24
use ApiPlatform\Metadata\GraphQl\Operation;
25
use ApiPlatform\Metadata\GraphQl\Query;
26
use ApiPlatform\Metadata\GraphQl\Subscription;
27
use ApiPlatform\Metadata\InflectorInterface;
28
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
29
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
30
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
31
use ApiPlatform\Metadata\ResourceClassResolverInterface;
32
use ApiPlatform\Metadata\Util\Inflector;
33
use ApiPlatform\State\Pagination\Pagination;
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\Type;
42
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
43
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
44
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
45

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

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

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

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

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

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

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

99
        return [];
×
100
    }
101

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

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

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

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

121
        return [];
×
122
    }
123

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

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

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

139
        return $mutationFields;
35✔
140
    }
141

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

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

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

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

165
        $subscriptionFields[$subscriptionName.$operation->getShortName().'Subscribe'] = $fieldConfiguration;
35✔
166

167
        return $subscriptionFields;
35✔
168
    }
169

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

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

186
            return [];
×
187
        }
188

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

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

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

205
            return $fields;
×
206
        }
207

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

215
        ++$depth; // increment the depth for the call to getResourceFieldConfiguration.
35✔
216

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

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

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

245
        if ($operation instanceof Mutation && $input) {
35✔
246
            $fields['clientMutationId'] = $clientMutationId;
×
247
        }
248

249
        return $fields;
35✔
250
    }
251

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

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

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

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

280
        return $enumCases;
4✔
281
    }
282

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

293
            $args[$id]['type'] = $this->typeConverter->resolveType($arg['type']);
35✔
294
        }
295

296
        return $args;
35✔
297
    }
298

299
    /**
300
     * Transform the result of a parse_str to a GraphQL object type.
301
     * We should consider merging getFilterArgs and this, `getFilterArgs` uses `convertType` whereas we assume that parameters have only scalar types.
302
     * Note that this method has a lower complexity then the `getFilterArgs` one.
303
     * TODO: Is there a use case with an argument being a complex type (eg: a Resource, Enum etc.)?
304
     *
305
     * @param array<array{name: string, required: bool|null, description: string|null, leafs: string|array, type: string}> $flattenFields
306
     */
307
    private function parameterToObjectType(array $flattenFields, string $name): InputObjectType
308
    {
309
        $fields = [];
35✔
310
        foreach ($flattenFields as $field) {
35✔
311
            $key = $field['name'];
35✔
312
            $type = $this->getParameterType(\in_array($field['type'], Type::$builtinTypes, true) ? new Type($field['type'], !$field['required']) : new Type('object', !$field['required'], $field['type']));
35✔
313

314
            if (\is_array($l = $field['leafs'])) {
35✔
315
                if (0 === key($l)) {
35✔
316
                    $key = $key;
35✔
317
                    $type = GraphQLType::listOf($type);
35✔
318
                } else {
319
                    $n = [];
35✔
320
                    foreach ($field['leafs'] as $l => $value) {
35✔
321
                        $n[] = ['required' => null, 'name' => $l, 'leafs' => $value, 'type' => 'string', 'description' => null];
35✔
322
                    }
323

324
                    $type = $this->parameterToObjectType($n, $key);
35✔
325
                    if (isset($fields[$key]) && ($t = $fields[$key]['type']) instanceof InputObjectType) {
35✔
326
                        $t = $fields[$key]['type'];
35✔
327
                        $t->config['fields'] = array_merge($t->config['fields'], $type->config['fields']);
35✔
328
                        $type = $t;
35✔
329
                    }
330
                }
331
            }
332

333
            if ($field['required']) {
35✔
334
                $type = GraphQLType::nonNull($type);
×
335
            }
336

337
            if (isset($fields[$key])) {
35✔
338
                if ($type instanceof ListOfType) {
35✔
339
                    $key .= '_list';
35✔
340
                }
341
            }
342

343
            $fields[$key] = ['type' => $type, 'name' => $key];
35✔
344
        }
345

346
        return new InputObjectType(['name' => $name, 'fields' => $fields]);
35✔
347
    }
348

349
    /**
350
     * A simplified version of convert type that does not support resources.
351
     */
352
    private function getParameterType(Type $type): GraphQLType
353
    {
354
        return match ($type->getBuiltinType()) {
35✔
355
            Type::BUILTIN_TYPE_BOOL => GraphQLType::boolean(),
35✔
356
            Type::BUILTIN_TYPE_INT => GraphQLType::int(),
35✔
357
            Type::BUILTIN_TYPE_FLOAT => GraphQLType::float(),
35✔
358
            Type::BUILTIN_TYPE_STRING => GraphQLType::string(),
35✔
359
            Type::BUILTIN_TYPE_ARRAY => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
35✔
360
            Type::BUILTIN_TYPE_ITERABLE => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
35✔
361
            Type::BUILTIN_TYPE_OBJECT => GraphQLType::string(),
35✔
362
            default => GraphQLType::string(),
35✔
363
        };
35✔
364
    }
365

366
    /**
367
     * Get the field configuration of a resource.
368
     *
369
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
370
     */
371
    private function getResourceFieldConfiguration(?string $property, ?string $fieldDescription, ?string $deprecationReason, Type $type, string $rootResource, bool $input, Operation $rootOperation, int $depth = 0, bool $forceNullable = false): ?array
372
    {
373
        try {
374
            $isCollectionType = $this->typeBuilder->isCollection($type);
35✔
375

376
            if (
377
                $isCollectionType
35✔
378
                && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
35✔
379
            ) {
380
                $resourceClass = $collectionValueType->getClassName();
35✔
381
            } else {
382
                $resourceClass = $type->getClassName();
35✔
383
            }
384

385
            $resourceOperation = $rootOperation;
35✔
386
            if ($resourceClass && $depth >= 1 && $this->resourceClassResolver->isResourceClass($resourceClass)) {
35✔
387
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
388
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
×
389
            }
390

391
            if (!$resourceOperation instanceof Operation) {
35✔
392
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
393
            }
394

395
            $graphqlType = $this->convertType($type, $input, $resourceOperation, $rootOperation, $resourceClass ?? '', $rootResource, $property, $depth, $forceNullable);
35✔
396

397
            $graphqlWrappedType = $graphqlType;
35✔
398
            if ($graphqlType instanceof WrappingType) {
35✔
399
                if (method_exists($graphqlType, 'getInnermostType')) {
35✔
400
                    $graphqlWrappedType = $graphqlType->getInnermostType();
35✔
401
                } else {
402
                    $graphqlWrappedType = $graphqlType->getWrappedType(true);
×
403
                }
404
            }
405
            $isStandardGraphqlType = \in_array($graphqlWrappedType, GraphQLType::getStandardTypes(), true);
35✔
406
            if ($isStandardGraphqlType) {
35✔
407
                $resourceClass = '';
35✔
408
            }
409

410
            // Check mercure attribute if it's a subscription at the root level.
411
            if ($rootOperation instanceof Subscription && null === $property && !$rootOperation->getMercure()) {
35✔
412
                return null;
×
413
            }
414

415
            $args = [];
35✔
416

417
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType) {
35✔
418
                if ($isCollectionType) {
35✔
419
                    if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
35✔
420
                        $args = $this->getGraphQlPaginationArgs($resourceOperation);
35✔
421
                    }
422

423
                    $args = $this->getFilterArgs($args, $resourceClass, $rootResource, $resourceOperation, $rootOperation, $property, $depth);
35✔
424
                    $args = $this->getParameterArgs($rootOperation, $args);
35✔
425
                }
426
            }
427

428
            if ($this->itemResolverFactory instanceof ResolverFactory) {
35✔
429
                if ($isStandardGraphqlType || $input) {
27✔
430
                    $resolve = null;
27✔
431
                } else {
432
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation, $this->propertyMetadataFactory);
27✔
433
                }
434
            } else {
435
                if ($isStandardGraphqlType || $input) {
8✔
436
                    $resolve = null;
8✔
437
                } elseif (($rootOperation instanceof Mutation || $rootOperation instanceof Subscription) && $depth <= 0) {
8✔
438
                    $resolve = $rootOperation instanceof Mutation ? ($this->itemMutationResolverFactory)($resourceClass, $rootResource, $resourceOperation) : ($this->itemSubscriptionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
8✔
439
                } elseif ($this->typeBuilder->isCollection($type)) {
8✔
440
                    $resolve = ($this->collectionResolverFactory)($resourceClass, $rootResource, $resourceOperation);
8✔
441
                } else {
442
                    $resolve = ($this->itemResolverFactory)($resourceClass, $rootResource, $resourceOperation);
8✔
443
                }
444
            }
445

446
            return [
35✔
447
                'type' => $graphqlType,
35✔
448
                'description' => $fieldDescription,
35✔
449
                'args' => $args,
35✔
450
                'resolve' => $resolve,
35✔
451
                'deprecationReason' => $deprecationReason,
35✔
452
            ];
35✔
453
        } catch (InvalidTypeException) {
4✔
454
            // just ignore invalid types
455
        }
456

457
        return null;
4✔
458
    }
459

460
    /*
461
     * This function is @experimental, read the comment on the parameterToObjectType function for additional information.
462
     * @experimental
463
     */
464
    private function getParameterArgs(Operation $operation, array $args = []): array
465
    {
466
        foreach ($operation->getParameters() ?? [] as $parameter) {
35✔
467
            $key = $parameter->getKey();
35✔
468

469
            if (!str_contains($key, ':property')) {
35✔
470
                $args[$key] = ['type' => GraphQLType::string()];
35✔
471

472
                if ($parameter->getRequired()) {
35✔
473
                    $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
474
                }
475

476
                continue;
35✔
477
            }
478

479
            if (!($filterId = $parameter->getFilter()) || !$this->filterLocator->has($filterId)) {
35✔
480
                continue;
×
481
            }
482

483
            $filter = $this->filterLocator->get($filterId);
35✔
484
            $parsedKey = explode('[:property]', $key);
35✔
485
            $flattenFields = [];
35✔
486

487
            if ($filter instanceof FilterInterface) {
35✔
488
                foreach ($filter->getDescription($operation->getClass()) as $name => $value) {
35✔
489
                    $values = [];
35✔
490
                    parse_str($name, $values);
35✔
491
                    if (isset($values[$parsedKey[0]])) {
35✔
492
                        $values = $values[$parsedKey[0]];
35✔
493
                    }
494

495
                    $name = key($values);
35✔
496
                    $flattenFields[] = ['name' => $name, 'required' => $value['required'] ?? null, 'description' => $value['description'] ?? null, 'leafs' => $values[$name], 'type' => $value['type'] ?? 'string'];
35✔
497
                }
498

499
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0]);
35✔
500
            }
501
        }
502

503
        return $args;
35✔
504
    }
505

506
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
507
    {
508
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
35✔
509

510
        if ('cursor' === $paginationType) {
35✔
511
            return [
35✔
512
                'first' => [
35✔
513
                    'type' => GraphQLType::int(),
35✔
514
                    'description' => 'Returns the first n elements from the list.',
35✔
515
                ],
35✔
516
                'last' => [
35✔
517
                    'type' => GraphQLType::int(),
35✔
518
                    'description' => 'Returns the last n elements from the list.',
35✔
519
                ],
35✔
520
                'before' => [
35✔
521
                    'type' => GraphQLType::string(),
35✔
522
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
35✔
523
                ],
35✔
524
                'after' => [
35✔
525
                    'type' => GraphQLType::string(),
35✔
526
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
35✔
527
                ],
35✔
528
            ];
35✔
529
        }
530

531
        $paginationOptions = $this->pagination->getOptions();
35✔
532

533
        $args = [
35✔
534
            $paginationOptions['page_parameter_name'] => [
35✔
535
                'type' => GraphQLType::int(),
35✔
536
                'description' => 'Returns the current page.',
35✔
537
            ],
35✔
538
        ];
35✔
539

540
        if ($paginationOptions['client_items_per_page']) {
35✔
541
            $args[$paginationOptions['items_per_page_parameter_name']] = [
35✔
542
                'type' => GraphQLType::int(),
35✔
543
                'description' => 'Returns the number of items per page.',
35✔
544
            ];
35✔
545
        }
546

547
        return $args;
35✔
548
    }
549

550
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
551
    {
552
        if (null === $resourceClass) {
35✔
553
            return $args;
×
554
        }
555

556
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
35✔
557
            if (!$this->filterLocator->has($filterId)) {
35✔
558
                continue;
×
559
            }
560

561
            $entityClass = $resourceClass;
35✔
562
            if ($options = $resourceOperation->getStateOptions()) {
35✔
563
                if (class_exists(Options::class) && $options instanceof Options && $options->getEntityClass()) {
35✔
564
                    $entityClass = $options->getEntityClass();
35✔
565
                }
566

567
                if (class_exists(ODMOptions::class) && $options instanceof ODMOptions && $options->getDocumentClass()) {
35✔
568
                    $entityClass = $options->getDocumentClass();
35✔
569
                }
570
            }
571

572
            foreach ($this->filterLocator->get($filterId)->getDescription($entityClass) as $key => $description) {
35✔
573
                $nullable = isset($description['required']) ? !$description['required'] : true;
35✔
574
                $filterType = \in_array($description['type'], Type::$builtinTypes, true) ? new Type($description['type'], $nullable) : new Type('object', $nullable, $description['type']);
35✔
575
                $graphqlFilterType = $this->convertType($filterType, false, $resourceOperation, $rootOperation, $resourceClass, $rootResource, $property, $depth);
35✔
576

577
                if (str_ends_with($key, '[]')) {
35✔
578
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
35✔
579
                    $key = substr($key, 0, -2).'_list';
35✔
580
                }
581

582
                /** @var string $key */
583
                $key = str_replace('.', $this->nestingSeparator, $key);
35✔
584

585
                parse_str($key, $parsed);
35✔
586
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
35✔
587
                    $parsed = [$key => ''];
×
588
                }
589
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
35✔
590
                    $v = $graphqlFilterType;
35✔
591
                });
35✔
592
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
35✔
593
            }
594
        }
595

596
        return $this->convertFilterArgsToTypes($args);
35✔
597
    }
598

599
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
600
    {
601
        foreach ($parsed as $key => $value) {
35✔
602
            // Never override keys that cannot be merged
603
            if (isset($args[$key]) && !\is_array($args[$key])) {
35✔
604
                continue;
35✔
605
            }
606

607
            if (\is_array($value)) {
35✔
608
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
35✔
609
                if (!isset($value['#name'])) {
35✔
610
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
35✔
611
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
35✔
612
                }
613
            }
614

615
            $args[$key] = $value;
35✔
616
        }
617

618
        return $args;
35✔
619
    }
620

621
    private function convertFilterArgsToTypes(array $args): array
622
    {
623
        foreach ($args as $key => $value) {
35✔
624
            if (strpos($key, '.')) {
35✔
625
                // Declare relations/nested fields in a GraphQL compatible syntax.
626
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
627
                unset($args[$key]);
×
628
            }
629
        }
630

631
        foreach ($args as $key => $value) {
35✔
632
            if (!\is_array($value) || !isset($value['#name'])) {
35✔
633
                continue;
35✔
634
            }
635

636
            $name = $value['#name'];
35✔
637

638
            if ($this->typesContainer->has($name)) {
35✔
639
                $args[$key] = $this->typesContainer->get($name);
×
640
                continue;
×
641
            }
642

643
            unset($value['#name']);
35✔
644

645
            $filterArgType = GraphQLType::listOf(new InputObjectType([
35✔
646
                'name' => $name,
35✔
647
                'fields' => $this->convertFilterArgsToTypes($value),
35✔
648
            ]));
35✔
649

650
            $this->typesContainer->set($name, $filterArgType);
35✔
651

652
            $args[$key] = $filterArgType;
35✔
653
        }
654

655
        return $args;
35✔
656
    }
657

658
    /**
659
     * Converts a built-in type to its GraphQL equivalent.
660
     *
661
     * @throws InvalidTypeException
662
     */
663
    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
664
    {
665
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
35✔
666

667
        if (null === $graphqlType) {
35✔
668
            throw new InvalidTypeException(\sprintf('The type "%s" is not supported.', $type->getBuiltinType()));
4✔
669
        }
670

671
        if (\is_string($graphqlType)) {
35✔
672
            if (!$this->typesContainer->has($graphqlType)) {
×
673
                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));
×
674
            }
675

676
            $graphqlType = $this->typesContainer->get($graphqlType);
×
677
        }
678

679
        if ($this->typeBuilder->isCollection($type)) {
35✔
680
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
35✔
681
                // Deprecated path, to remove in API Platform 4.
682
                if ($this->typeBuilder instanceof TypeBuilderInterface) {
35✔
683
                    return $this->typeBuilder->getResourcePaginatedCollectionType($graphqlType, $resourceClass, $resourceOperation);
×
684
                }
685

686
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
35✔
687
            }
688

689
            return GraphQLType::listOf($graphqlType);
35✔
690
        }
691

692
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
35✔
693
            ? $graphqlType
35✔
694
            : GraphQLType::nonNull($graphqlType);
35✔
695
    }
696

697
    private function normalizePropertyName(string $property, string $resourceClass): string
698
    {
699
        if (null === $this->nameConverter) {
35✔
700
            return $property;
×
701
        }
702
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
35✔
703
            return $this->nameConverter->normalize($property, $resourceClass);
35✔
704
        }
705

706
        return $this->nameConverter->normalize($property);
×
707
    }
708
}
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