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

api-platform / core / 15255731762

26 May 2025 01:55PM UTC coverage: 0.0% (-26.5%) from 26.526%
15255731762

Pull #7176

github

web-flow
Merge 66f6cf4d2 into 79edced67
Pull Request #7176: Merge 4.1

0 of 387 new or added lines in 28 files covered. (0.0%)

11394 existing lines in 372 files now uncovered.

0 of 51334 relevant lines covered (0.0%)

0.0 hits per line

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

0.0
/src/GraphQl/Type/FieldsBuilder.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace ApiPlatform\GraphQl\Type;
15

16
use ApiPlatform\GraphQl\Exception\InvalidTypeException;
17
use ApiPlatform\GraphQl\Resolver\Factory\ResolverFactoryInterface;
18
use ApiPlatform\GraphQl\Type\Definition\TypeInterface;
19
use ApiPlatform\Metadata\FilterInterface;
20
use ApiPlatform\Metadata\GraphQl\Mutation;
21
use ApiPlatform\Metadata\GraphQl\Operation;
22
use ApiPlatform\Metadata\GraphQl\Query;
23
use ApiPlatform\Metadata\GraphQl\Subscription;
24
use ApiPlatform\Metadata\InflectorInterface;
25
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
26
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
27
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
28
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
29
use ApiPlatform\Metadata\ResourceClassResolverInterface;
30
use ApiPlatform\Metadata\Util\Inflector;
31
use ApiPlatform\Metadata\Util\PropertyInfoToTypeInfoHelper;
32
use ApiPlatform\Metadata\Util\TypeHelper;
33
use ApiPlatform\State\Pagination\Pagination;
34
use 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\PropertyInfoExtractor;
42
use Symfony\Component\PropertyInfo\Type as LegacyType;
43
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
44
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
45
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
46
use Symfony\Component\TypeInfo\Type;
47
use Symfony\Component\TypeInfo\Type\CollectionType;
48
use Symfony\Component\TypeInfo\Type\ObjectType;
49
use Symfony\Component\TypeInfo\TypeIdentifier;
50

51
/**
52
 * Builds the GraphQL fields.
53
 *
54
 * @author Alan Poulain <contact@alanpoulain.eu>
55
 */
56
final class FieldsBuilder implements FieldsBuilderEnumInterface
57
{
58
    private readonly ContextAwareTypeBuilderInterface $typeBuilder;
59

60
    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())
61
    {
UNCOV
62
        $this->typeBuilder = $typeBuilder;
×
63
    }
64

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

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

UNCOV
88
        $fieldName = lcfirst('item_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
×
89

UNCOV
90
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), Type::nullable(Type::object($resourceClass)), $resourceClass, false, $operation)) {
×
UNCOV
91
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
×
UNCOV
92
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
×
UNCOV
93
            $configuration['args'] = $args ?: $configuration['args'] ?? ['id' => ['type' => GraphQLType::nonNull(GraphQLType::id())]] + $extraArgs;
×
94

UNCOV
95
            return [$fieldName => array_merge($fieldConfiguration, $configuration)];
×
96
        }
97

98
        return [];
×
99
    }
100

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

UNCOV
110
        $fieldName = lcfirst('collection_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
×
111

UNCOV
112
        if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), Type::collection(Type::object(\stdClass::class), Type::object($resourceClass)), $resourceClass, false, $operation)) {
×
UNCOV
113
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
×
UNCOV
114
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
×
UNCOV
115
            $configuration['args'] = $args ?: $configuration['args'] ?? $fieldConfiguration['args'] + $extraArgs;
×
116

UNCOV
117
            return [$this->inflector->pluralize($fieldName) => array_merge($fieldConfiguration, $configuration)];
×
118
        }
119

120
        return [];
×
121
    }
122

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

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

UNCOV
136
        $mutationFields[$operation->getName().$operation->getShortName()] = $fieldConfiguration ?? [];
×
137

UNCOV
138
        return $mutationFields;
×
139
    }
140

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

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

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

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

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

166
        return $subscriptionFields;
×
167
    }
168

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

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

185
            return [];
×
186
        }
187

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

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

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

204
            return $fields;
×
205
        }
206

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

UNCOV
214
        ++$depth; // increment the depth for the call to getResourceFieldConfiguration.
×
215

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

UNCOV
224
                if (!method_exists(PropertyInfoExtractor::class, 'getType')) {
×
225
                    $propertyTypes = $propertyMetadata->getBuiltinTypes();
×
226

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

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

UNCOV
252
                    if ($fieldConfiguration = $this->getResourceFieldConfiguration($property, $propertyMetadata->getDescription(), $propertyMetadata->getDeprecationReason(), $propertyType, $resourceClass, $input, $operation, $depth, null !== $propertyMetadata->getSecurity())) {
×
UNCOV
253
                        $fields['id' === $property ? '_id' : $this->normalizePropertyName($property, $resourceClass)] = $fieldConfiguration;
×
254
                    }
255
                }
256
            }
257
        }
258

UNCOV
259
        if ($operation instanceof Mutation && $input) {
×
UNCOV
260
            $fields['clientMutationId'] = $clientMutationId;
×
261
        }
262

UNCOV
263
        return $fields;
×
264
    }
265

266
    private function isEnumClass(string $resourceClass): bool
267
    {
UNCOV
268
        return is_a($resourceClass, \BackedEnum::class, true);
×
269
    }
270

271
    /**
272
     * {@inheritdoc}
273
     */
274
    public function getEnumFields(string $enumClass): array
275
    {
UNCOV
276
        $rEnum = new \ReflectionEnum($enumClass);
×
277

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

UNCOV
287
            $propertyMetadata = $this->propertyMetadataFactory->create($enumClass, $rCase->getName());
×
UNCOV
288
            if ($enumCaseDescription = $propertyMetadata->getDescription()) {
×
UNCOV
289
                $enumCase['description'] = $enumCaseDescription;
×
290
            }
UNCOV
291
            $enumCases[$rCase->getName()] = $enumCase;
×
292
        }
293

UNCOV
294
        return $enumCases;
×
295
    }
296

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

307
            $args[$id]['type'] = $this->typeConverter->resolveType($arg['type']);
×
308
        }
309

UNCOV
310
        return $args;
×
311
    }
312

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

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

UNCOV
342
                    $type = $this->parameterToObjectType($n, $key);
×
UNCOV
343
                    if (isset($fields[$key]) && ($t = $fields[$key]['type']) instanceof InputObjectType) {
×
UNCOV
344
                        $t = $fields[$key]['type'];
×
UNCOV
345
                        $t->config['fields'] = array_merge($t->config['fields'], $type->config['fields']);
×
UNCOV
346
                        $type = $t;
×
347
                    }
348
                }
349
            }
350

UNCOV
351
            if ($field['required']) {
×
352
                $type = GraphQLType::nonNull($type);
×
353
            }
354

UNCOV
355
            if (isset($fields[$key])) {
×
UNCOV
356
                if ($type instanceof ListOfType) {
×
UNCOV
357
                    $key .= '_list';
×
358
                }
359
            }
360

UNCOV
361
            $fields[$key] = ['type' => $type, 'name' => $key];
×
362
        }
363

UNCOV
364
        return new InputObjectType(['name' => $name, 'fields' => $fields]);
×
365
    }
366

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

UNCOV
376
        if ($type->isIdentifiedBy(TypeIdentifier::INT)) {
×
377
            return GraphQLType::int();
×
378
        }
379

UNCOV
380
        if ($type->isIdentifiedBy(TypeIdentifier::FLOAT)) {
×
381
            return GraphQLType::float();
×
382
        }
383

UNCOV
384
        if ($type->isIdentifiedBy(TypeIdentifier::STRING, TypeIdentifier::OBJECT)) {
×
UNCOV
385
            return GraphQLType::string();
×
386
        }
387

388
        if ($type instanceof CollectionType) {
×
389
            return GraphQLType::listOf($this->getParameterType($type->getCollectionValueType()));
×
390
        }
391

392
        return GraphQLType::string();
×
393
    }
394

395
    /**
396
     * Get the field configuration of a resource.
397
     *
398
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
399
     */
400
    private function getResourceFieldConfiguration(?string $property, ?string $fieldDescription, ?string $deprecationReason, Type|LegacyType $type, string $rootResource, bool $input, Operation $rootOperation, int $depth = 0, bool $forceNullable = false): ?array
401
    {
UNCOV
402
        if ($type instanceof LegacyType) {
×
403
            $type = PropertyInfoToTypeInfoHelper::convertLegacyTypesToType([$type]);
×
404
        }
405

406
        try {
UNCOV
407
            $isCollectionType = $type->isSatisfiedBy(fn ($t) => $t instanceof CollectionType) && ($v = TypeHelper::getCollectionValueType($type)) && TypeHelper::getClassName($v);
×
408

UNCOV
409
            $valueType = $type;
×
UNCOV
410
            if ($isCollectionType) {
×
UNCOV
411
                $valueType = TypeHelper::getCollectionValueType($type);
×
412
            }
413

414
            /** @var class-string|null $resourceClass */
UNCOV
415
            $resourceClass = null;
×
UNCOV
416
            $typeIsResourceClass = function (Type $type) use (&$resourceClass): bool {
×
UNCOV
417
                return $type instanceof ObjectType && $this->resourceClassResolver->isResourceClass($resourceClass = $type->getClassName());
×
UNCOV
418
            };
×
419

UNCOV
420
            $isResourceClass = $valueType->isSatisfiedBy($typeIsResourceClass);
×
421

UNCOV
422
            $resourceOperation = $rootOperation;
×
UNCOV
423
            if ($resourceClass && $depth >= 1 && $isResourceClass) {
×
UNCOV
424
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
UNCOV
425
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
×
426
            }
427

UNCOV
428
            if (!$resourceOperation instanceof Operation) {
×
429
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
430
            }
431

UNCOV
432
            $graphqlType = $this->convertType($type, $input, $resourceOperation, $rootOperation, $resourceClass ?? '', $rootResource, $property, $depth, $forceNullable);
×
433

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

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

UNCOV
452
            $args = [];
×
453

UNCOV
454
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType) {
×
UNCOV
455
                if ($isCollectionType) {
×
UNCOV
456
                    if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
×
UNCOV
457
                        $args = $this->getGraphQlPaginationArgs($resourceOperation);
×
458
                    }
459

UNCOV
460
                    $args = $this->getFilterArgs($args, $resourceClass, $rootResource, $resourceOperation, $rootOperation, $property, $depth);
×
461

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

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

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

UNCOV
490
        return null;
×
491
    }
492

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

UNCOV
502
            if (!str_contains($key, ':property')) {
×
UNCOV
503
                $args[$key] = ['type' => GraphQLType::string()];
×
504

UNCOV
505
                if ($parameter->getRequired()) {
×
506
                    $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
507
                }
508

UNCOV
509
                continue;
×
510
            }
511

UNCOV
512
            if (!($filterId = $parameter->getFilter()) || !$this->filterLocator->has($filterId)) {
×
513
                continue;
×
514
            }
515

UNCOV
516
            $filter = $this->filterLocator->get($filterId);
×
UNCOV
517
            $parsedKey = explode('[:property]', $key);
×
UNCOV
518
            $flattenFields = [];
×
519

UNCOV
520
            if ($filter instanceof FilterInterface) {
×
UNCOV
521
                foreach ($filter->getDescription($operation->getClass()) as $name => $value) {
×
UNCOV
522
                    $values = [];
×
UNCOV
523
                    parse_str($name, $values);
×
UNCOV
524
                    if (isset($values[$parsedKey[0]])) {
×
UNCOV
525
                        $values = $values[$parsedKey[0]];
×
526
                    }
527

UNCOV
528
                    $name = key($values);
×
UNCOV
529
                    $flattenFields[] = ['name' => $name, 'required' => $value['required'] ?? null, 'description' => $value['description'] ?? null, 'leafs' => $values[$name], 'type' => $value['type'] ?? 'string'];
×
530
                }
531

UNCOV
532
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0]);
×
533
            }
534

UNCOV
535
            if ($filter instanceof OpenApiParameterFilterInterface) {
×
UNCOV
536
                foreach ($filter->getOpenApiParameters($parameter) as $value) {
×
UNCOV
537
                    $values = [];
×
UNCOV
538
                    parse_str($value->getName(), $values);
×
UNCOV
539
                    if (isset($values[$parsedKey[0]])) {
×
UNCOV
540
                        $values = $values[$parsedKey[0]];
×
541
                    }
542

UNCOV
543
                    $name = key($values);
×
UNCOV
544
                    $flattenFields[] = ['name' => $name, 'required' => $value->getRequired(), 'description' => $value->getDescription(), 'leafs' => $values[$name], 'type' => $value->getSchema()['type'] ?? 'string'];
×
545
                }
546

UNCOV
547
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0].$operation->getShortName().$operation->getName());
×
548
            }
549
        }
550

UNCOV
551
        return $args;
×
552
    }
553

554
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
555
    {
UNCOV
556
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
×
557

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

579
        $paginationOptions = $this->pagination->getOptions();
×
580

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

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

595
        return $args;
×
596
    }
597

598
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
599
    {
UNCOV
600
        if (null === $resourceClass) {
×
601
            return $args;
×
602
        }
603

UNCOV
604
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
×
605
            if (!$this->filterLocator->has($filterId)) {
×
606
                continue;
×
607
            }
608

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

616
                if (str_ends_with($key, '[]')) {
×
617
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
×
618
                    $key = substr($key, 0, -2).'_list';
×
619
                }
620

621
                /** @var string $key */
622
                $key = str_replace('.', $this->nestingSeparator, $key);
×
623

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

UNCOV
635
        return $this->convertFilterArgsToTypes($args);
×
636
    }
637

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

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

654
            $args[$key] = $value;
×
655
        }
656

657
        return $args;
×
658
    }
659

660
    private function convertFilterArgsToTypes(array $args): array
661
    {
UNCOV
662
        foreach ($args as $key => $value) {
×
UNCOV
663
            if (strpos($key, '.')) {
×
664
                // Declare relations/nested fields in a GraphQL compatible syntax.
665
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
666
                unset($args[$key]);
×
667
            }
668
        }
669

UNCOV
670
        foreach ($args as $key => $value) {
×
UNCOV
671
            if (!\is_array($value) || !isset($value['#name'])) {
×
UNCOV
672
                continue;
×
673
            }
674

675
            $name = $value['#name'];
×
676

677
            if ($this->typesContainer->has($name)) {
×
678
                $args[$key] = $this->typesContainer->get($name);
×
679
                continue;
×
680
            }
681

682
            unset($value['#name']);
×
683

684
            $filterArgType = GraphQLType::listOf(new InputObjectType([
×
685
                'name' => $name,
×
686
                'fields' => $this->convertFilterArgsToTypes($value),
×
687
            ]));
×
688

689
            $this->typesContainer->set($name, $filterArgType);
×
690

691
            $args[$key] = $filterArgType;
×
692
        }
693

UNCOV
694
        return $args;
×
695
    }
696

697
    /**
698
     * Converts a built-in type to its GraphQL equivalent.
699
     *
700
     * @throws InvalidTypeException
701
     */
702
    private function convertType(Type|LegacyType $type, bool $input, Operation $resourceOperation, Operation $rootOperation, string $resourceClass, string $rootResource, ?string $property, int $depth, bool $forceNullable = false): GraphQLType|ListOfType|NonNull
703
    {
UNCOV
704
        if ($type instanceof LegacyType) {
×
705
            $type = PropertyInfoToTypeInfoHelper::convertLegacyTypesToType([$type]);
×
706
        }
707

UNCOV
708
        $graphqlType = $this->typeConverter->convertPhpType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
×
709

UNCOV
710
        if (null === $graphqlType) {
×
UNCOV
711
            throw new InvalidTypeException(\sprintf('The type "%s" is not supported.', (string) $type));
×
712
        }
713

UNCOV
714
        if (\is_string($graphqlType)) {
×
715
            if (!$this->typesContainer->has($graphqlType)) {
×
716
                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));
×
717
            }
718

719
            $graphqlType = $this->typesContainer->get($graphqlType);
×
720
        }
721

UNCOV
722
        if ($type->isSatisfiedBy(fn ($t) => $t instanceof CollectionType) && ($collectionValueType = TypeHelper::getCollectionValueType($type)) && TypeHelper::getClassName($collectionValueType)) {
×
UNCOV
723
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
×
UNCOV
724
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
×
725
            }
726

UNCOV
727
            return GraphQLType::listOf($graphqlType);
×
728
        }
729

UNCOV
730
        return $forceNullable || !$graphqlType instanceof NullableType || $type->isNullable() || ($rootOperation instanceof Mutation && 'update' === $rootOperation->getName())
×
UNCOV
731
            ? $graphqlType
×
UNCOV
732
            : GraphQLType::nonNull($graphqlType);
×
733
    }
734

735
    private function normalizePropertyName(string $property, string $resourceClass): string
736
    {
UNCOV
737
        if (null === $this->nameConverter) {
×
738
            return $property;
×
739
        }
UNCOV
740
        if ($this->nameConverter instanceof AdvancedNameConverterInterface || $this->nameConverter instanceof MetadataAwareNameConverter) {
×
UNCOV
741
            return $this->nameConverter->normalize($property, $resourceClass);
×
742
        }
743

744
        return $this->nameConverter->normalize($property);
×
745
    }
746
}
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

© 2025 Coveralls, Inc