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

api-platform / core / 13200284839

07 Feb 2025 12:56PM UTC coverage: 0.0% (-8.2%) from 8.164%
13200284839

Pull #6952

github

web-flow
Merge 519fbf8cc into 62377f880
Pull Request #6952: fix: errors retrieval and documentation

0 of 206 new or added lines in 17 files covered. (0.0%)

10757 existing lines in 366 files now uncovered.

0 of 47781 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\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;
×
58
    }
59

60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function getNodeQueryFields(): array
64
    {
UNCOV
65
        return [
×
UNCOV
66
            'type' => $this->typeBuilder->getNodeInterface(),
×
UNCOV
67
            'args' => [
×
UNCOV
68
                'id' => ['type' => GraphQLType::nonNull(GraphQLType::id())],
×
UNCOV
69
            ],
×
UNCOV
70
            'resolve' => ($this->resolverFactory)(),
×
UNCOV
71
        ];
×
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()) {
×
UNCOV
80
            return [];
×
81
        }
82

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

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

UNCOV
90
            return [$fieldName => array_merge($fieldConfiguration, $configuration)];
×
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()) {
×
UNCOV
102
            return [];
×
103
        }
104

UNCOV
105
        $fieldName = lcfirst('collection_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());
×
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)) {
×
UNCOV
108
            $args = $this->resolveResourceArgs($configuration['args'] ?? [], $operation);
×
UNCOV
109
            $extraArgs = $this->resolveResourceArgs($operation->getExtraArgs() ?? [], $operation);
×
UNCOV
110
            $configuration['args'] = $args ?: $configuration['args'] ?? $fieldConfiguration['args'] + $extraArgs;
×
111

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

115
        return [];
×
116
    }
117

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

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

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

UNCOV
133
        return $mutationFields;
×
134
    }
135

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

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

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

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

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

161
        return $subscriptionFields;
×
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 = [];
×
UNCOV
170
        $idField = ['type' => GraphQLType::nonNull(GraphQLType::id())];
×
UNCOV
171
        $optionalIdField = ['type' => GraphQLType::id()];
×
UNCOV
172
        $clientMutationId = GraphQLType::string();
×
UNCOV
173
        $clientSubscriptionId = GraphQLType::string();
×
174

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

180
            return [];
×
181
        }
182

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

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

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

199
            return $fields;
×
200
        }
201

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

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

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

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

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

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

UNCOV
243
        return $fields;
×
244
    }
245

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

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

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

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

UNCOV
274
        return $enumCases;
×
275
    }
276

277
    /**
278
     * {@inheritdoc}
279
     */
280
    public function resolveResourceArgs(array $args, Operation $operation): array
281
    {
UNCOV
282
        foreach ($args as $id => $arg) {
×
283
            if (!isset($arg['type'])) {
×
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']);
×
288
        }
289

UNCOV
290
        return $args;
×
291
    }
292

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

UNCOV
308
            if (\is_array($l = $field['leafs'])) {
×
UNCOV
309
                if (0 === key($l)) {
×
UNCOV
310
                    $key = $key;
×
UNCOV
311
                    $type = GraphQLType::listOf($type);
×
312
                } else {
UNCOV
313
                    $n = [];
×
UNCOV
314
                    foreach ($field['leafs'] as $l => $value) {
×
UNCOV
315
                        $n[] = ['required' => null, 'name' => $l, 'leafs' => $value, 'type' => 'string', 'description' => null];
×
316
                    }
317

UNCOV
318
                    $type = $this->parameterToObjectType($n, $key);
×
UNCOV
319
                    if (isset($fields[$key]) && ($t = $fields[$key]['type']) instanceof InputObjectType) {
×
UNCOV
320
                        $t = $fields[$key]['type'];
×
UNCOV
321
                        $t->config['fields'] = array_merge($t->config['fields'], $type->config['fields']);
×
UNCOV
322
                        $type = $t;
×
323
                    }
324
                }
325
            }
326

UNCOV
327
            if ($field['required']) {
×
328
                $type = GraphQLType::nonNull($type);
×
329
            }
330

UNCOV
331
            if (isset($fields[$key])) {
×
UNCOV
332
                if ($type instanceof ListOfType) {
×
UNCOV
333
                    $key .= '_list';
×
334
                }
335
            }
336

UNCOV
337
            $fields[$key] = ['type' => $type, 'name' => $key];
×
338
        }
339

UNCOV
340
        return new InputObjectType(['name' => $name, 'fields' => $fields]);
×
341
    }
342

343
    /**
344
     * A simplified version of convert type that does not support resources.
345
     */
346
    private function getParameterType(Type $type): GraphQLType
347
    {
UNCOV
348
        return match ($type->getBuiltinType()) {
×
349
            Type::BUILTIN_TYPE_BOOL => GraphQLType::boolean(),
×
350
            Type::BUILTIN_TYPE_INT => GraphQLType::int(),
×
351
            Type::BUILTIN_TYPE_FLOAT => GraphQLType::float(),
×
UNCOV
352
            Type::BUILTIN_TYPE_STRING => GraphQLType::string(),
×
353
            Type::BUILTIN_TYPE_ARRAY => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
×
354
            Type::BUILTIN_TYPE_ITERABLE => GraphQLType::listOf($this->getParameterType($type->getCollectionValueTypes()[0])),
×
UNCOV
355
            Type::BUILTIN_TYPE_OBJECT => GraphQLType::string(),
×
UNCOV
356
            default => GraphQLType::string(),
×
UNCOV
357
        };
×
358
    }
359

360
    /**
361
     * Get the field configuration of a resource.
362
     *
363
     * @see http://webonyx.github.io/graphql-php/type-system/object-types/
364
     */
365
    private function getResourceFieldConfiguration(?string $property, ?string $fieldDescription, ?string $deprecationReason, Type $type, string $rootResource, bool $input, Operation $rootOperation, int $depth = 0, bool $forceNullable = false): ?array
366
    {
367
        try {
UNCOV
368
            $isCollectionType = $this->typeBuilder->isCollection($type);
×
369

370
            if (
UNCOV
371
                $isCollectionType
×
UNCOV
372
                && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
×
373
            ) {
UNCOV
374
                $resourceClass = $collectionValueType->getClassName();
×
375
            } else {
UNCOV
376
                $resourceClass = $type->getClassName();
×
377
            }
378

UNCOV
379
            $resourceOperation = $rootOperation;
×
UNCOV
380
            if ($resourceClass && $depth >= 1 && $this->resourceClassResolver->isResourceClass($resourceClass)) {
×
381
                $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
382
                $resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
×
383
            }
384

UNCOV
385
            if (!$resourceOperation instanceof Operation) {
×
386
                throw new \LogicException('The resource operation should be a GraphQL operation.');
×
387
            }
388

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

UNCOV
391
            $graphqlWrappedType = $graphqlType;
×
UNCOV
392
            if ($graphqlType instanceof WrappingType) {
×
UNCOV
393
                if (method_exists($graphqlType, 'getInnermostType')) {
×
UNCOV
394
                    $graphqlWrappedType = $graphqlType->getInnermostType();
×
395
                } else {
396
                    $graphqlWrappedType = $graphqlType->getWrappedType(true);
×
397
                }
398
            }
UNCOV
399
            $isStandardGraphqlType = \in_array($graphqlWrappedType, GraphQLType::getStandardTypes(), true);
×
UNCOV
400
            if ($isStandardGraphqlType) {
×
UNCOV
401
                $resourceClass = '';
×
402
            }
403

404
            // Check mercure attribute if it's a subscription at the root level.
UNCOV
405
            if ($rootOperation instanceof Subscription && null === $property && !$rootOperation->getMercure()) {
×
406
                return null;
×
407
            }
408

UNCOV
409
            $args = [];
×
410

UNCOV
411
            if (!$input && !$rootOperation instanceof Mutation && !$rootOperation instanceof Subscription && !$isStandardGraphqlType) {
×
UNCOV
412
                if ($isCollectionType) {
×
UNCOV
413
                    if (!$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
×
UNCOV
414
                        $args = $this->getGraphQlPaginationArgs($resourceOperation);
×
415
                    }
416

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

419
                    // Also register parameter args in the types container
420
                    // Note: This is a workaround, for more information read the comment on the parameterToObjectType function.
UNCOV
421
                    foreach ($this->getParameterArgs($rootOperation) as $key => $arg) {
×
UNCOV
422
                        if ($arg instanceof InputObjectType || (\is_array($arg) && isset($arg['name']))) {
×
UNCOV
423
                            $this->typesContainer->set(\is_array($arg) ? $arg['name'] : $arg->name(), $arg);
×
424
                        }
UNCOV
425
                        $args[$key] = $arg;
×
426
                    }
427
                }
428
            }
429

UNCOV
430
            if ($isStandardGraphqlType || $input) {
×
UNCOV
431
                $resolve = null;
×
432
            } else {
UNCOV
433
                $resolve = ($this->resolverFactory)($resourceClass, $rootResource, $resourceOperation, $this->propertyMetadataFactory);
×
434
            }
435

UNCOV
436
            return [
×
UNCOV
437
                'type' => $graphqlType,
×
UNCOV
438
                'description' => $fieldDescription,
×
UNCOV
439
                'args' => $args,
×
UNCOV
440
                'resolve' => $resolve,
×
UNCOV
441
                'deprecationReason' => $deprecationReason,
×
UNCOV
442
            ];
×
UNCOV
443
        } catch (InvalidTypeException) {
×
444
            // just ignore invalid types
445
        }
446

UNCOV
447
        return null;
×
448
    }
449

450
    /*
451
     * This function is @experimental, read the comment on the parameterToObjectType function for additional information.
452
     * @experimental
453
     */
454
    private function getParameterArgs(Operation $operation, array $args = []): array
455
    {
UNCOV
456
        foreach ($operation->getParameters() ?? [] as $parameter) {
×
UNCOV
457
            $key = $parameter->getKey();
×
458

UNCOV
459
            if (!str_contains($key, ':property')) {
×
UNCOV
460
                $args[$key] = ['type' => GraphQLType::string()];
×
461

UNCOV
462
                if ($parameter->getRequired()) {
×
463
                    $args[$key]['type'] = GraphQLType::nonNull($args[$key]['type']);
×
464
                }
465

UNCOV
466
                continue;
×
467
            }
468

UNCOV
469
            if (!($filterId = $parameter->getFilter()) || !$this->filterLocator->has($filterId)) {
×
470
                continue;
×
471
            }
472

UNCOV
473
            $filter = $this->filterLocator->get($filterId);
×
UNCOV
474
            $parsedKey = explode('[:property]', $key);
×
UNCOV
475
            $flattenFields = [];
×
476

UNCOV
477
            if ($filter instanceof FilterInterface) {
×
UNCOV
478
                foreach ($filter->getDescription($operation->getClass()) as $name => $value) {
×
UNCOV
479
                    $values = [];
×
UNCOV
480
                    parse_str($name, $values);
×
UNCOV
481
                    if (isset($values[$parsedKey[0]])) {
×
UNCOV
482
                        $values = $values[$parsedKey[0]];
×
483
                    }
484

UNCOV
485
                    $name = key($values);
×
UNCOV
486
                    $flattenFields[] = ['name' => $name, 'required' => $value['required'] ?? null, 'description' => $value['description'] ?? null, 'leafs' => $values[$name], 'type' => $value['type'] ?? 'string'];
×
487
                }
488

UNCOV
489
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0]);
×
490
            }
491

UNCOV
492
            if ($filter instanceof OpenApiParameterFilterInterface) {
×
UNCOV
493
                foreach ($filter->getOpenApiParameters($parameter) as $value) {
×
UNCOV
494
                    $values = [];
×
UNCOV
495
                    parse_str($value->getName(), $values);
×
UNCOV
496
                    if (isset($values[$parsedKey[0]])) {
×
UNCOV
497
                        $values = $values[$parsedKey[0]];
×
498
                    }
499

UNCOV
500
                    $name = key($values);
×
UNCOV
501
                    $flattenFields[] = ['name' => $name, 'required' => $value->getRequired(), 'description' => $value->getDescription(), 'leafs' => $values[$name], 'type' => $value->getSchema()['type'] ?? 'string'];
×
502
                }
503

UNCOV
504
                $args[$parsedKey[0]] = $this->parameterToObjectType($flattenFields, $parsedKey[0].$operation->getShortName().$operation->getName());
×
505
            }
506
        }
507

UNCOV
508
        return $args;
×
509
    }
510

511
    private function getGraphQlPaginationArgs(Operation $queryOperation): array
512
    {
UNCOV
513
        $paginationType = $this->pagination->getGraphQlPaginationType($queryOperation);
×
514

UNCOV
515
        if ('cursor' === $paginationType) {
×
UNCOV
516
            return [
×
UNCOV
517
                'first' => [
×
UNCOV
518
                    'type' => GraphQLType::int(),
×
UNCOV
519
                    'description' => 'Returns the first n elements from the list.',
×
UNCOV
520
                ],
×
UNCOV
521
                'last' => [
×
UNCOV
522
                    'type' => GraphQLType::int(),
×
UNCOV
523
                    'description' => 'Returns the last n elements from the list.',
×
UNCOV
524
                ],
×
UNCOV
525
                'before' => [
×
UNCOV
526
                    'type' => GraphQLType::string(),
×
UNCOV
527
                    'description' => 'Returns the elements in the list that come before the specified cursor.',
×
UNCOV
528
                ],
×
UNCOV
529
                'after' => [
×
UNCOV
530
                    'type' => GraphQLType::string(),
×
UNCOV
531
                    'description' => 'Returns the elements in the list that come after the specified cursor.',
×
UNCOV
532
                ],
×
UNCOV
533
            ];
×
534
        }
535

536
        $paginationOptions = $this->pagination->getOptions();
×
537

538
        $args = [
×
539
            $paginationOptions['page_parameter_name'] => [
×
540
                'type' => GraphQLType::int(),
×
541
                'description' => 'Returns the current page.',
×
542
            ],
×
543
        ];
×
544

545
        if ($paginationOptions['client_items_per_page']) {
×
546
            $args[$paginationOptions['items_per_page_parameter_name']] = [
×
547
                'type' => GraphQLType::int(),
×
548
                'description' => 'Returns the number of items per page.',
×
549
            ];
×
550
        }
551

552
        return $args;
×
553
    }
554

555
    private function getFilterArgs(array $args, ?string $resourceClass, string $rootResource, Operation $resourceOperation, Operation $rootOperation, ?string $property, int $depth): array
556
    {
UNCOV
557
        if (null === $resourceClass) {
×
558
            return $args;
×
559
        }
560

UNCOV
561
        foreach ($resourceOperation->getFilters() ?? [] as $filterId) {
×
562
            if (!$this->filterLocator->has($filterId)) {
×
563
                continue;
×
564
            }
565

566
            $entityClass = $resourceClass;
×
567
            if ($options = $resourceOperation->getStateOptions()) {
×
568
                if (class_exists(Options::class) && $options instanceof Options && $options->getEntityClass()) {
×
569
                    $entityClass = $options->getEntityClass();
×
570
                }
571

572
                if (class_exists(ODMOptions::class) && $options instanceof ODMOptions && $options->getDocumentClass()) {
×
573
                    $entityClass = $options->getDocumentClass();
×
574
                }
575
            }
576

577
            foreach ($this->filterLocator->get($filterId)->getDescription($entityClass) as $key => $description) {
×
578
                $nullable = isset($description['required']) ? !$description['required'] : true;
×
579
                $filterType = \in_array($description['type'], Type::$builtinTypes, true) ? new Type($description['type'], $nullable) : new Type('object', $nullable, $description['type']);
×
580
                $graphqlFilterType = $this->convertType($filterType, false, $resourceOperation, $rootOperation, $resourceClass, $rootResource, $property, $depth);
×
581

582
                if (str_ends_with($key, '[]')) {
×
583
                    $graphqlFilterType = GraphQLType::listOf($graphqlFilterType);
×
584
                    $key = substr($key, 0, -2).'_list';
×
585
                }
586

587
                /** @var string $key */
588
                $key = str_replace('.', $this->nestingSeparator, $key);
×
589

590
                parse_str($key, $parsed);
×
591
                if (\array_key_exists($key, $parsed) && \is_array($parsed[$key])) {
×
592
                    $parsed = [$key => ''];
×
593
                }
594
                array_walk_recursive($parsed, static function (&$v) use ($graphqlFilterType): void {
×
595
                    $v = $graphqlFilterType;
×
596
                });
×
597
                $args = $this->mergeFilterArgs($args, $parsed, $resourceOperation, $key);
×
598
            }
599
        }
600

UNCOV
601
        return $this->convertFilterArgsToTypes($args);
×
602
    }
603

604
    private function mergeFilterArgs(array $args, array $parsed, ?Operation $operation = null, string $original = ''): array
605
    {
606
        foreach ($parsed as $key => $value) {
×
607
            // Never override keys that cannot be merged
608
            if (isset($args[$key]) && !\is_array($args[$key])) {
×
609
                continue;
×
610
            }
611

612
            if (\is_array($value)) {
×
613
                $value = $this->mergeFilterArgs($args[$key] ?? [], $value);
×
614
                if (!isset($value['#name'])) {
×
615
                    $name = (false === $pos = strrpos($original, '[')) ? $original : substr($original, 0, (int) $pos);
×
616
                    $value['#name'] = ($operation ? $operation->getShortName() : '').'Filter_'.strtr($name, ['[' => '_', ']' => '', '.' => '__']);
×
617
                }
618
            }
619

620
            $args[$key] = $value;
×
621
        }
622

623
        return $args;
×
624
    }
625

626
    private function convertFilterArgsToTypes(array $args): array
627
    {
UNCOV
628
        foreach ($args as $key => $value) {
×
UNCOV
629
            if (strpos($key, '.')) {
×
630
                // Declare relations/nested fields in a GraphQL compatible syntax.
631
                $args[str_replace('.', $this->nestingSeparator, $key)] = $value;
×
632
                unset($args[$key]);
×
633
            }
634
        }
635

UNCOV
636
        foreach ($args as $key => $value) {
×
UNCOV
637
            if (!\is_array($value) || !isset($value['#name'])) {
×
UNCOV
638
                continue;
×
639
            }
640

641
            $name = $value['#name'];
×
642

643
            if ($this->typesContainer->has($name)) {
×
644
                $args[$key] = $this->typesContainer->get($name);
×
645
                continue;
×
646
            }
647

648
            unset($value['#name']);
×
649

650
            $filterArgType = GraphQLType::listOf(new InputObjectType([
×
651
                'name' => $name,
×
652
                'fields' => $this->convertFilterArgsToTypes($value),
×
653
            ]));
×
654

655
            $this->typesContainer->set($name, $filterArgType);
×
656

657
            $args[$key] = $filterArgType;
×
658
        }
659

UNCOV
660
        return $args;
×
661
    }
662

663
    /**
664
     * Converts a built-in type to its GraphQL equivalent.
665
     *
666
     * @throws InvalidTypeException
667
     */
668
    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
669
    {
UNCOV
670
        $graphqlType = $this->typeConverter->convertType($type, $input, $rootOperation, $resourceClass, $rootResource, $property, $depth);
×
671

UNCOV
672
        if (null === $graphqlType) {
×
UNCOV
673
            throw new InvalidTypeException(\sprintf('The type "%s" is not supported.', $type->getBuiltinType()));
×
674
        }
675

UNCOV
676
        if (\is_string($graphqlType)) {
×
677
            if (!$this->typesContainer->has($graphqlType)) {
×
678
                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));
×
679
            }
680

681
            $graphqlType = $this->typesContainer->get($graphqlType);
×
682
        }
683

UNCOV
684
        if ($this->typeBuilder->isCollection($type)) {
×
UNCOV
685
            if (!$input && !$this->isEnumClass($resourceClass) && $this->pagination->isGraphQlEnabled($resourceOperation)) {
×
UNCOV
686
                return $this->typeBuilder->getPaginatedCollectionType($graphqlType, $resourceOperation);
×
687
            }
688

UNCOV
689
            return GraphQLType::listOf($graphqlType);
×
690
        }
691

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

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

706
        return $this->nameConverter->normalize($property);
×
707
    }
708
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc