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

api-platform / core / 11229883409

08 Oct 2024 06:32AM UTC coverage: 7.833% (+0.03%) from 7.804%
11229883409

push

github

web-flow
test(laravel): call factories, debug is now false by default (#6702)

1 of 79 new or added lines in 11 files covered. (1.27%)

1730 existing lines in 107 files now uncovered.

12939 of 165183 relevant lines covered (7.83%)

27.01 hits per line

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

91.48
/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\FilterInterface;
22
use ApiPlatform\Metadata\GraphQl\Mutation;
23
use ApiPlatform\Metadata\GraphQl\Operation;
24
use ApiPlatform\Metadata\GraphQl\Query;
25
use ApiPlatform\Metadata\GraphQl\Subscription;
26
use ApiPlatform\Metadata\InflectorInterface;
27
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
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 FieldsBuilderEnumInterface
52
{
53
    private readonly ContextAwareTypeBuilderInterface $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 $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())
56
    {
57
        $this->typeBuilder = $typeBuilder;
441✔
58
    }
59

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

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

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

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

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

93
        return [];
×
94
    }
95

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

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

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

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

115
        return [];
×
116
    }
117

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

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

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

133
        return $mutationFields;
411✔
134
    }
135

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

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

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

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

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

UNCOV
161
        return $subscriptionFields;
408✔
162
    }
163

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

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

UNCOV
180
            return [];
9✔
181
        }
182

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

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

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

UNCOV
199
            return $fields;
14✔
200
        }
201

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

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

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

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

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

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

243
        return $fields;
414✔
244
    }
245

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

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

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

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

274
        return $enumCases;
16✔
275
    }
276

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

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

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

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

301
                $filter = $this->filterLocator->get($filterId);
411✔
302
                $parsedKey = explode('[:property]', $key);
411✔
303
                $flattenFields = [];
411✔
304

305
                if ($filter instanceof FilterInterface) {
411✔
306
                    foreach ($filter->getDescription($operation->getClass()) as $name => $value) {
411✔
307
                        $values = [];
411✔
308
                        parse_str($name, $values);
411✔
309
                        if (isset($values[$parsedKey[0]])) {
411✔
310
                            $values = $values[$parsedKey[0]];
411✔
311
                        }
312

313
                        $name = key($values);
411✔
314
                        $flattenFields[] = ['name' => $name, 'required' => $value['required'] ?? null, 'description' => $value['description'] ?? null, 'leafs' => $values[$name], 'type' => $value['type'] ?? 'string'];
411✔
315
                    }
316

317
                    $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0]);
411✔
318
                }
319

320
                if ($filter instanceof OpenApiParameterFilterInterface) {
411✔
321
                    foreach ($filter->getOpenApiParameters($parameter) as $value) {
×
322
                        $values = [];
×
323
                        parse_str($value->getName(), $values);
×
324
                        if (isset($values[$parsedKey[0]])) {
×
325
                            $values = $values[$parsedKey[0]];
×
326
                        }
327

328
                        $name = key($values);
×
329
                        $flattenFields[] = ['name' => $name, 'required' => $value->getRequired(), 'description' => $value->getDescription(), 'leafs' => $values[$name], 'type' => $value->getSchema()['type'] ?? 'string'];
×
330
                    }
331

332
                    $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0].$operation->getShortName().$operation->getName());
×
333
                }
334

335
                continue;
411✔
336
            }
337

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

340
            if ($parameter->getRequired()) {
411✔
341
                $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
342
            }
343
        }
344

345
        return $args;
435✔
346
    }
347

348
    /**
349
     * Transform the result of a parse_str to a GraphQL object type.
350
     * We should consider merging getFilterArgs and this, `getFilterArgs` uses `convertType` whereas we assume that parameters have only scalar types.
351
     * Note that this method has a lower complexity then the `getFilterArgs` one.
352
     * TODO: Is there a use case with an argument being a complex type (eg: a Resource, Enum etc.)?
353
     *
354
     * @param array<array{name: string, required: bool|null, description: string|null, leafs: string|array, type: string}> $flattenFields
355
     */
356
    private function parameterToObjectType(array $flattenFields, string $name): InputObjectType
357
    {
358
        $fields = [];
411✔
359
        foreach ($flattenFields as $field) {
411✔
360
            $key = $field['name'];
411✔
361
            $type = $this->getParameterType(\in_array($field['type'], Type::$builtinTypes, true) ? new Type($field['type'], !$field['required']) : new Type('object', !$field['required'], $field['type']));
411✔
362

363
            if (\is_array($l = $field['leafs'])) {
411✔
364
                if (0 === key($l)) {
411✔
365
                    $key = $key;
411✔
366
                    $type = GraphQLType::listOf($type);
411✔
367
                } else {
368
                    $n = [];
411✔
369
                    foreach ($field['leafs'] as $l => $value) {
411✔
370
                        $n[] = ['required' => null, 'name' => $l, 'leafs' => $value, 'type' => 'string', 'description' => null];
411✔
371
                    }
372

373
                    $type = $this->parameterToObjectType($n, $key);
411✔
374
                    if (isset($fields[$key]) && ($t = $fields[$key]['type']) instanceof InputObjectType) {
411✔
375
                        $t = $fields[$key]['type'];
411✔
376
                        $t->config['fields'] = array_merge($t->config['fields'], $type->config['fields']);
411✔
377
                        $type = $t;
411✔
378
                    }
379
                }
380
            }
381

382
            if ($field['required']) {
411✔
383
                $type = GraphQLType::nonNull($type);
×
384
            }
385

386
            if (isset($fields[$key])) {
411✔
387
                if ($type instanceof ListOfType) {
411✔
388
                    $key .= '_list';
411✔
389
                }
390
            }
391

392
            $fields[$key] = ['type' => $type, 'name' => $key];
411✔
393
        }
394

395
        return new InputObjectType(['name' => $name, 'fields' => $fields]);
411✔
396
    }
397

398
    /**
399
     * A simplified version of convert type that does not support resources.
400
     */
401
    private function getParameterType(Type $type): GraphQLType
402
    {
403
        return match ($type->getBuiltinType()) {
411✔
UNCOV
404
            Type::BUILTIN_TYPE_BOOL => GraphQLType::boolean(),
408✔
UNCOV
405
            Type::BUILTIN_TYPE_INT => GraphQLType::int(),
408✔
UNCOV
406
            Type::BUILTIN_TYPE_FLOAT => GraphQLType::float(),
408✔
407
            Type::BUILTIN_TYPE_STRING => GraphQLType::string(),
411✔
UNCOV
408
            Type::BUILTIN_TYPE_ARRAY => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
408✔
UNCOV
409
            Type::BUILTIN_TYPE_ITERABLE => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
408✔
410
            Type::BUILTIN_TYPE_OBJECT => GraphQLType::string(),
411✔
411
            default => GraphQLType::string(),
411✔
412
        };
411✔
413
    }
414

415
    /**
416
     * Get the field configuration of a resource.
417
     *
418
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
419
     */
420
    private function getResourceFieldConfiguration(?string $property, ?string $fieldDescription, ?string $deprecationReason, Type $type, string $rootResource, bool $input, Operation $rootOperation, int $depth = 0, bool $forceNullable = false): ?array
421
    {
422
        try {
423
            $isCollectionType = $this->typeBuilder->isCollection($type);
435✔
424

425
            if (
426
                $isCollectionType
435✔
427
                && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
435✔
428
            ) {
429
                $resourceClass = $collectionValueType->getClassName();
435✔
430
            } else {
431
                $resourceClass = $type->getClassName();
435✔
432
            }
433

434
            $resourceOperation = $rootOperation;
435✔
435
            if ($resourceClass && $depth >= 1 && $this->resourceClassResolver->isResourceClass($resourceClass)) {
435✔
UNCOV
436
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
279✔
UNCOV
437
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
279✔
438
            }
439

440
            if (!$resourceOperation instanceof Operation) {
435✔
441
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
442
            }
443

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

446
            $graphqlWrappedType = $graphqlType;
435✔
447
            if ($graphqlType instanceof WrappingType) {
435✔
448
                if (method_exists($graphqlType, 'getInnermostType')) {
435✔
449
                    $graphqlWrappedType = $graphqlType->getInnermostType();
435✔
450
                } else {
451
                    $graphqlWrappedType = $graphqlType->getWrappedType(true);
×
452
                }
453
            }
454
            $isStandardGraphqlType = \in_array($graphqlWrappedType, GraphQLType::getStandardTypes(), true);
435✔
455
            if ($isStandardGraphqlType) {
435✔
456
                $resourceClass = '';
414✔
457
            }
458

459
            // Check mercure attribute if it's a subscription at the root level.
460
            if ($rootOperation instanceof Subscription && null === $property && !$rootOperation->getMercure()) {
435✔
461
                return null;
×
462
            }
463

464
            $args = [];
435✔
465

466
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType && $isCollectionType) {
435✔
467
                if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
435✔
468
                    $args = $this->getGraphQlPaginationArgs($resourceOperation);
414✔
469
                }
470

471
                $args = $this->getFilterArgs($args, $resourceClass, $rootResource, $resourceOperation, $rootOperation, $property, $depth);
435✔
472
            }
473

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

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

491
        return null;
89✔
492
    }
493

494
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
495
    {
496
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
414✔
497

498
        if ('cursor' === $paginationType) {
414✔
499
            return [
414✔
500
                'first' => [
414✔
501
                    'type' => GraphQLType::int(),
414✔
502
                    'description' => 'Returns the first n elements from the list.',
414✔
503
                ],
414✔
504
                'last' => [
414✔
505
                    'type' => GraphQLType::int(),
414✔
506
                    'description' => 'Returns the last n elements from the list.',
414✔
507
                ],
414✔
508
                'before' => [
414✔
509
                    'type' => GraphQLType::string(),
414✔
510
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
414✔
511
                ],
414✔
512
                'after' => [
414✔
513
                    'type' => GraphQLType::string(),
414✔
514
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
414✔
515
                ],
414✔
516
            ];
414✔
517
        }
518

UNCOV
519
        $paginationOptions = $this->pagination->getOptions();
408✔
520

UNCOV
521
        $args = [
408✔
UNCOV
522
            $paginationOptions['page_parameter_name'] => [
408✔
UNCOV
523
                'type' => GraphQLType::int(),
408✔
UNCOV
524
                'description' => 'Returns the current page.',
408✔
UNCOV
525
            ],
408✔
UNCOV
526
        ];
408✔
527

UNCOV
528
        if ($paginationOptions['client_items_per_page']) {
408✔
UNCOV
529
            $args[$paginationOptions['items_per_page_parameter_name']] = [
408✔
UNCOV
530
                'type' => GraphQLType::int(),
408✔
UNCOV
531
                'description' => 'Returns the number of items per page.',
408✔
UNCOV
532
            ];
408✔
533
        }
534

UNCOV
535
        return $args;
408✔
536
    }
537

538
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
539
    {
540
        if (null === $resourceClass) {
435✔
541
            return $args;
×
542
        }
543

544
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
435✔
UNCOV
545
            if (!$this->filterLocator->has($filterId)) {
408✔
546
                continue;
×
547
            }
548

UNCOV
549
            $entityClass = $resourceClass;
408✔
UNCOV
550
            if ($options = $resourceOperation->getStateOptions()) {
408✔
UNCOV
551
                if (class_exists(Options::class) && $options instanceof Options && $options->getEntityClass()) {
408✔
UNCOV
552
                    $entityClass = $options->getEntityClass();
408✔
553
                }
554

UNCOV
555
                if (class_exists(ODMOptions::class) && $options instanceof ODMOptions && $options->getDocumentClass()) {
408✔
UNCOV
556
                    $entityClass = $options->getDocumentClass();
408✔
557
                }
558
            }
559

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

UNCOV
565
                if (str_ends_with($key, '[]')) {
408✔
UNCOV
566
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
408✔
UNCOV
567
                    $key = substr($key, 0, -2).'_list';
408✔
568
                }
569

570
                /** @var string $key */
UNCOV
571
                $key = str_replace('.', $this->nestingSeparator, $key);
408✔
572

UNCOV
573
                parse_str($key, $parsed);
408✔
UNCOV
574
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
408✔
575
                    $parsed = [$key => ''];
×
576
                }
UNCOV
577
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
408✔
UNCOV
578
                    $v = $graphqlFilterType;
408✔
UNCOV
579
                });
408✔
UNCOV
580
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
408✔
581
            }
582
        }
583

584
        return $this->convertFilterArgsToTypes($args);
435✔
585
    }
586

587
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
588
    {
UNCOV
589
        foreach ($parsed as $key => $value) {
408✔
590
            // Never override keys that cannot be merged
UNCOV
591
            if (isset($args[$key]) && !\is_array($args[$key])) {
408✔
UNCOV
592
                continue;
408✔
593
            }
594

UNCOV
595
            if (\is_array($value)) {
408✔
UNCOV
596
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
408✔
UNCOV
597
                if (!isset($value['#name'])) {
408✔
UNCOV
598
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
408✔
UNCOV
599
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
408✔
600
                }
601
            }
602

UNCOV
603
            $args[$key] = $value;
408✔
604
        }
605

UNCOV
606
        return $args;
408✔
607
    }
608

609
    private function convertFilterArgsToTypes(array $args): array
610
    {
611
        foreach ($args as $key => $value) {
435✔
612
            if (strpos($key, '.')) {
414✔
613
                // Declare relations/nested fields in a GraphQL compatible syntax.
614
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
615
                unset($args[$key]);
×
616
            }
617
        }
618

619
        foreach ($args as $key => $value) {
435✔
620
            if (!\is_array($value) || !isset($value['#name'])) {
414✔
621
                continue;
414✔
622
            }
623

UNCOV
624
            $name = $value['#name'];
408✔
625

UNCOV
626
            if ($this->typesContainer->has($name)) {
408✔
UNCOV
627
                $args[$key] = $this->typesContainer->get($name);
26✔
UNCOV
628
                continue;
26✔
629
            }
630

UNCOV
631
            unset($value['#name']);
408✔
632

UNCOV
633
            $filterArgType = GraphQLType::listOf(new InputObjectType([
408✔
UNCOV
634
                'name' => $name,
408✔
UNCOV
635
                'fields' => $this->convertFilterArgsToTypes($value),
408✔
UNCOV
636
            ]));
408✔
637

UNCOV
638
            $this->typesContainer->set($name, $filterArgType);
408✔
639

UNCOV
640
            $args[$key] = $filterArgType;
408✔
641
        }
642

643
        return $args;
435✔
644
    }
645

646
    /**
647
     * Converts a built-in type to its GraphQL equivalent.
648
     *
649
     * @throws InvalidTypeException
650
     */
651
    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
652
    {
653
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
435✔
654

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

659
        if (\is_string($graphqlType)) {
435✔
UNCOV
660
            if (!$this->typesContainer->has($graphqlType)) {
311✔
661
                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));
×
662
            }
663

UNCOV
664
            $graphqlType = $this->typesContainer->get($graphqlType);
311✔
665
        }
666

667
        if ($this->typeBuilder->isCollection($type)) {
435✔
668
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
435✔
669
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
414✔
670
            }
671

672
            return GraphQLType::listOf($graphqlType);
432✔
673
        }
674

675
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
435✔
676
            ? $graphqlType
435✔
677
            : GraphQLType::nonNull($graphqlType);
435✔
678
    }
679

680
    private function normalizePropertyName(string $property, string $resourceClass): string
681
    {
682
        if (null === $this->nameConverter) {
408✔
683
            return $property;
×
684
        }
685
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
408✔
686
            return $this->nameConverter->normalize($property, $resourceClass);
408✔
687
        }
688

689
        return $this->nameConverter->normalize($property);
×
690
    }
691
}
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