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

api-platform / core / 11182119487

04 Oct 2024 02:50PM UTC coverage: 7.837% (+0.4%) from 7.441%
11182119487

push

github

soyuka
Merge 4.0

0 of 266 new or added lines in 25 files covered. (0.0%)

9900 existing lines in 360 files now uncovered.

12939 of 165109 relevant lines covered (7.84%)

27.02 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
    {
UNCOV
57
        $this->typeBuilder = $typeBuilder;
441✔
58
    }
59

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

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

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

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

UNCOV
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
    {
UNCOV
101
        if ($operation instanceof Query && $operation->getNested()) {
435✔
UNCOV
102
            return [];
435✔
103
        }
104

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

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

UNCOV
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
    {
UNCOV
123
        $mutationFields = [];
411✔
UNCOV
124
        $resourceType = new Type(Type::BUILTIN_TYPE_OBJECT, true, $resourceClass);
411✔
UNCOV
125
        $description = $operation->getDescription() ?? ucfirst("{$operation->getName()}s a {$operation->getShortName()}.");
411✔
126

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

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

UNCOV
133
        return $mutationFields;
411✔
134
    }
135

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

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

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

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

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

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
    {
UNCOV
169
        $fields = [];
417✔
UNCOV
170
        $idField = ['type' => GraphQLType::nonNull(GraphQLType::id())];
417✔
UNCOV
171
        $optionalIdField = ['type' => GraphQLType::id()];
417✔
UNCOV
172
        $clientMutationId = GraphQLType::string();
417✔
UNCOV
173
        $clientSubscriptionId = GraphQLType::string();
417✔
174

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

180
            return [];
9✔
181
        }
182

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

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

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

199
            return $fields;
14✔
200
        }
201

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

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

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

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

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

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

UNCOV
243
        return $fields;
414✔
244
    }
245

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

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

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

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

UNCOV
274
        return $enumCases;
16✔
275
    }
276

277
    /**
278
     * {@inheritdoc}
279
     */
280
    public function resolveResourceArgs(array $args, Operation $operation): array
281
    {
UNCOV
282
        foreach ($args as $id => $arg) {
435✔
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

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
         */
UNCOV
293
        foreach ($operation->getParameters() ?? [] as $parameter) {
435✔
UNCOV
294
            $key = $parameter->getKey();
411✔
295

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

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

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

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

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

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

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

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

UNCOV
335
                continue;
411✔
336
            }
337

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

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

UNCOV
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
    {
UNCOV
358
        $fields = [];
411✔
UNCOV
359
        foreach ($flattenFields as $field) {
411✔
UNCOV
360
            $key = $field['name'];
411✔
UNCOV
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

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

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

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

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

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

UNCOV
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
    {
UNCOV
403
        return match ($type->getBuiltinType()) {
411✔
404
            Type::BUILTIN_TYPE_BOOL => GraphQLType::boolean(),
408✔
405
            Type::BUILTIN_TYPE_INT => GraphQLType::int(),
408✔
406
            Type::BUILTIN_TYPE_FLOAT => GraphQLType::float(),
408✔
UNCOV
407
            Type::BUILTIN_TYPE_STRING => GraphQLType::string(),
411✔
408
            Type::BUILTIN_TYPE_ARRAY => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
408✔
409
            Type::BUILTIN_TYPE_ITERABLE => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
408✔
UNCOV
410
            Type::BUILTIN_TYPE_OBJECT => GraphQLType::string(),
411✔
UNCOV
411
            default => GraphQLType::string(),
411✔
UNCOV
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 {
UNCOV
423
            $isCollectionType = $this->typeBuilder->isCollection($type);
435✔
424

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

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

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

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

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

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

UNCOV
464
            $args = [];
435✔
465

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

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

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

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

UNCOV
491
        return null;
89✔
492
    }
493

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

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

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

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

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

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
    {
UNCOV
540
        if (null === $resourceClass) {
435✔
541
            return $args;
×
542
        }
543

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

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

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

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

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

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

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

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

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

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

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

606
        return $args;
408✔
607
    }
608

609
    private function convertFilterArgsToTypes(array $args): array
610
    {
UNCOV
611
        foreach ($args as $key => $value) {
435✔
UNCOV
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

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

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

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

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

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

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

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

UNCOV
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
    {
UNCOV
653
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
435✔
654

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

UNCOV
659
        if (\is_string($graphqlType)) {
435✔
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

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

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

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

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

680
    private function normalizePropertyName(string $property, string $resourceClass): string
681
    {
UNCOV
682
        if (null === $this->nameConverter) {
408✔
683
            return $property;
×
684
        }
UNCOV
685
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
408✔
UNCOV
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