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

api-platform / core / 10963383095

20 Sep 2024 05:06PM UTC coverage: 7.834%. Remained the same
10963383095

push

github

soyuka
test(laravel): standard put model should update when it exists

0 of 5 new or added lines in 1 file covered. (0.0%)

342 existing lines in 15 files now uncovered.

12915 of 164861 relevant lines covered (7.83%)

27.03 hits per line

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

93.79
/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\ResolverFactoryInterface;
20
use ApiPlatform\GraphQl\Type\Definition\TypeInterface;
21
use ApiPlatform\Metadata\GraphQl\Mutation;
22
use ApiPlatform\Metadata\GraphQl\Operation;
23
use ApiPlatform\Metadata\GraphQl\Query;
24
use ApiPlatform\Metadata\GraphQl\Subscription;
25
use ApiPlatform\Metadata\InflectorInterface;
26
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
27
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
28
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
29
use ApiPlatform\Metadata\ResourceClassResolverInterface;
30
use ApiPlatform\Metadata\Util\Inflector;
31
use ApiPlatform\State\Pagination\Pagination;
32
use GraphQL\Type\Definition\InputObjectType;
33
use GraphQL\Type\Definition\ListOfType;
34
use GraphQL\Type\Definition\NonNull;
35
use GraphQL\Type\Definition\NullableType;
36
use GraphQL\Type\Definition\Type as GraphQLType;
37
use GraphQL\Type\Definition\WrappingType;
38
use Psr\Container\ContainerInterface;
39
use Symfony\Component\PropertyInfo\Type;
40
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
41
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
42
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
43

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

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

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

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

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

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

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

91
        return [];
×
92
    }
93

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

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

105
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), new Type(Type::BUILTIN_TYPE_OBJECT, false, null, true, null, new Type(Type::BUILTIN_TYPE_OBJECT, false, $resourceClass)), $resourceClass, false, $operation)) {
435✔
106
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
435✔
107
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
435✔
108
            $configuration['args'] = $args ?: $configuration['args'] ?? $fieldConfiguration['args'] + $extraArgs;
435✔
109

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

113
        return [];
×
114
    }
115

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

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

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

131
        return $mutationFields;
411✔
132
    }
133

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

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

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

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

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

UNCOV
159
        return $subscriptionFields;
408✔
160
    }
161

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

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

UNCOV
178
            return [];
9✔
179
        }
180

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

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

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

UNCOV
197
            return $fields;
14✔
198
        }
199

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

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

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

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

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

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

241
        return $fields;
414✔
242
    }
243

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

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

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

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

272
        return $enumCases;
16✔
273
    }
274

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

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

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

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

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

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

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

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

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

323
        return $args;
435✔
324
    }
325

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

442
            $args = [];
435✔
443

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

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

452
            if ($isStandardGraphqlType || $input) {
435✔
453
                $resolve = null;
435✔
454
            } else {
455
                $resolve = ($this->resolverFactory)($resourceClass, $rootResource, $resourceOperation, $this->propertyMetadataFactory);
435✔
456
            }
457

458
            return [
435✔
459
                'type' => $graphqlType,
435✔
460
                'description' => $fieldDescription,
435✔
461
                'args' => $args,
435✔
462
                'resolve' => $resolve,
435✔
463
                'deprecationReason' => $deprecationReason,
435✔
464
            ];
435✔
465
        } catch (InvalidTypeException) {
89✔
466
            // just ignore invalid types
467
        }
468

469
        return null;
89✔
470
    }
471

472
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
473
    {
474
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
414✔
475

476
        if ('cursor' === $paginationType) {
414✔
477
            return [
414✔
478
                'first' => [
414✔
479
                    'type' => GraphQLType::int(),
414✔
480
                    'description' => 'Returns the first n elements from the list.',
414✔
481
                ],
414✔
482
                'last' => [
414✔
483
                    'type' => GraphQLType::int(),
414✔
484
                    'description' => 'Returns the last n elements from the list.',
414✔
485
                ],
414✔
486
                'before' => [
414✔
487
                    'type' => GraphQLType::string(),
414✔
488
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
414✔
489
                ],
414✔
490
                'after' => [
414✔
491
                    'type' => GraphQLType::string(),
414✔
492
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
414✔
493
                ],
414✔
494
            ];
414✔
495
        }
496

UNCOV
497
        $paginationOptions = $this->pagination->getOptions();
408✔
498

UNCOV
499
        $args = [
408✔
UNCOV
500
            $paginationOptions['page_parameter_name'] => [
408✔
UNCOV
501
                'type' => GraphQLType::int(),
408✔
UNCOV
502
                'description' => 'Returns the current page.',
408✔
UNCOV
503
            ],
408✔
UNCOV
504
        ];
408✔
505

UNCOV
506
        if ($paginationOptions['client_items_per_page']) {
408✔
UNCOV
507
            $args[$paginationOptions['items_per_page_parameter_name']] = [
408✔
UNCOV
508
                'type' => GraphQLType::int(),
408✔
UNCOV
509
                'description' => 'Returns the number of items per page.',
408✔
UNCOV
510
            ];
408✔
511
        }
512

UNCOV
513
        return $args;
408✔
514
    }
515

516
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
517
    {
518
        if (null === $resourceClass) {
435✔
519
            return $args;
×
520
        }
521

522
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
435✔
UNCOV
523
            if (!$this->filterLocator->has($filterId)) {
408✔
524
                continue;
×
525
            }
526

UNCOV
527
            $entityClass = $resourceClass;
408✔
UNCOV
528
            if ($options = $resourceOperation->getStateOptions()) {
408✔
UNCOV
529
                if (class_exists(Options::class) && $options instanceof Options && $options->getEntityClass()) {
408✔
UNCOV
530
                    $entityClass = $options->getEntityClass();
408✔
531
                }
532

UNCOV
533
                if (class_exists(ODMOptions::class) && $options instanceof ODMOptions && $options->getDocumentClass()) {
408✔
UNCOV
534
                    $entityClass = $options->getDocumentClass();
408✔
535
                }
536
            }
537

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

UNCOV
543
                if (str_ends_with($key, '[]')) {
408✔
UNCOV
544
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
408✔
UNCOV
545
                    $key = substr($key, 0, -2).'_list';
408✔
546
                }
547

548
                /** @var string $key */
UNCOV
549
                $key = str_replace('.', $this->nestingSeparator, $key);
408✔
550

UNCOV
551
                parse_str($key, $parsed);
408✔
UNCOV
552
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
408✔
553
                    $parsed = [$key => ''];
×
554
                }
UNCOV
555
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
408✔
UNCOV
556
                    $v = $graphqlFilterType;
408✔
UNCOV
557
                });
408✔
UNCOV
558
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
408✔
559
            }
560
        }
561

562
        return $this->convertFilterArgsToTypes($args);
435✔
563
    }
564

565
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
566
    {
UNCOV
567
        foreach ($parsed as $key => $value) {
408✔
568
            // Never override keys that cannot be merged
UNCOV
569
            if (isset($args[$key]) && !\is_array($args[$key])) {
408✔
UNCOV
570
                continue;
408✔
571
            }
572

UNCOV
573
            if (\is_array($value)) {
408✔
UNCOV
574
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
408✔
UNCOV
575
                if (!isset($value['#name'])) {
408✔
UNCOV
576
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
408✔
UNCOV
577
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
408✔
578
                }
579
            }
580

UNCOV
581
            $args[$key] = $value;
408✔
582
        }
583

UNCOV
584
        return $args;
408✔
585
    }
586

587
    private function convertFilterArgsToTypes(array $args): array
588
    {
589
        foreach ($args as $key => $value) {
435✔
590
            if (strpos($key, '.')) {
414✔
591
                // Declare relations/nested fields in a GraphQL compatible syntax.
592
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
593
                unset($args[$key]);
×
594
            }
595
        }
596

597
        foreach ($args as $key => $value) {
435✔
598
            if (!\is_array($value) || !isset($value['#name'])) {
414✔
599
                continue;
414✔
600
            }
601

UNCOV
602
            $name = $value['#name'];
408✔
603

UNCOV
604
            if ($this->typesContainer->has($name)) {
408✔
UNCOV
605
                $args[$key] = $this->typesContainer->get($name);
26✔
UNCOV
606
                continue;
26✔
607
            }
608

UNCOV
609
            unset($value['#name']);
408✔
610

UNCOV
611
            $filterArgType = GraphQLType::listOf(new InputObjectType([
408✔
UNCOV
612
                'name' => $name,
408✔
UNCOV
613
                'fields' => $this->convertFilterArgsToTypes($value),
408✔
UNCOV
614
            ]));
408✔
615

UNCOV
616
            $this->typesContainer->set($name, $filterArgType);
408✔
617

UNCOV
618
            $args[$key] = $filterArgType;
408✔
619
        }
620

621
        return $args;
435✔
622
    }
623

624
    /**
625
     * Converts a built-in type to its GraphQL equivalent.
626
     *
627
     * @throws InvalidTypeException
628
     */
629
    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
630
    {
631
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
435✔
632

633
        if (null === $graphqlType) {
435✔
634
            throw new InvalidTypeException(\sprintf('The type "%s" is not supported.', $type->getBuiltinType()));
89✔
635
        }
636

637
        if (\is_string($graphqlType)) {
435✔
UNCOV
638
            if (!$this->typesContainer->has($graphqlType)) {
311✔
639
                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));
×
640
            }
641

UNCOV
642
            $graphqlType = $this->typesContainer->get($graphqlType);
311✔
643
        }
644

645
        if ($this->typeBuilder->isCollection($type)) {
435✔
646
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
435✔
647
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
414✔
648
            }
649

650
            return GraphQLType::listOf($graphqlType);
432✔
651
        }
652

653
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
435✔
654
            ? $graphqlType
435✔
655
            : GraphQLType::nonNull($graphqlType);
435✔
656
    }
657

658
    private function normalizePropertyName(string $property, string $resourceClass): string
659
    {
660
        if (null === $this->nameConverter) {
408✔
661
            return $property;
×
662
        }
663
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
408✔
664
            return $this->nameConverter->normalize($property, $resourceClass);
408✔
665
        }
666

667
        return $this->nameConverter->normalize($property);
×
668
    }
669
}
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