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

api-platform / core / 10749392760

07 Sep 2024 06:39AM UTC coverage: 7.646%. Remained the same
10749392760

push

github

soyuka
test: remove hydra prefix from guides

0 of 21 new or added lines in 6 files covered. (0.0%)

6834 existing lines in 225 files now uncovered.

12538 of 163980 relevant lines covered (7.65%)

22.78 hits per line

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

94.85
/src/GraphQl/Type/TypeBuilder.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\Serializer\ItemNormalizer;
17
use ApiPlatform\Metadata\ApiProperty;
18
use ApiPlatform\Metadata\CollectionOperationInterface;
19
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
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\Resource\ResourceMetadataCollection;
25
use ApiPlatform\State\Pagination\Pagination;
26
use GraphQL\Type\Definition\EnumType;
27
use GraphQL\Type\Definition\InputObjectType;
28
use GraphQL\Type\Definition\InterfaceType;
29
use GraphQL\Type\Definition\NonNull;
30
use GraphQL\Type\Definition\ObjectType;
31
use GraphQL\Type\Definition\Type as GraphQLType;
32
use Psr\Container\ContainerInterface;
33
use Symfony\Component\PropertyInfo\Type;
34

35
/**
36
 * Builds the GraphQL types.
37
 *
38
 * @author Alan Poulain <contact@alanpoulain.eu>
39
 */
40
final class TypeBuilder implements ContextAwareTypeBuilderInterface
41
{
42
    private $defaultFieldResolver;
43

44
    public function __construct(private readonly TypesContainerInterface $typesContainer, callable $defaultFieldResolver, private ?ContainerInterface $fieldsBuilderLocator, private readonly Pagination $pagination)
45
    {
UNCOV
46
        $this->fieldsBuilderLocator = $fieldsBuilderLocator;
414✔
UNCOV
47
        $this->defaultFieldResolver = $defaultFieldResolver;
414✔
48
    }
49

50
    public function setFieldsBuilderLocator(ContainerInterface $fieldsBuilderLocator): void
51
    {
52
        $this->fieldsBuilderLocator = $fieldsBuilderLocator;
×
53
    }
54

55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function getResourceObjectType(ResourceMetadataCollection $resourceMetadataCollection, Operation $operation, ?ApiProperty $propertyMetadata = null, array $context = []): GraphQLType
59
    {
UNCOV
60
        $shortName = $operation->getShortName();
408✔
UNCOV
61
        $operationName = $operation->getName();
408✔
UNCOV
62
        $input = $context['input'];
408✔
UNCOV
63
        $depth = $context['depth'] ?? 0;
408✔
UNCOV
64
        $wrapped = $context['wrapped'] ?? false;
408✔
65

UNCOV
66
        if ($operation instanceof Mutation) {
408✔
UNCOV
67
            $shortName = $operationName.ucfirst($shortName);
408✔
68
        }
69

UNCOV
70
        if ($operation instanceof Subscription) {
408✔
UNCOV
71
            $shortName = $operationName.ucfirst($shortName).'Subscription';
408✔
72
        }
73

UNCOV
74
        if ($input) {
408✔
UNCOV
75
            if ($depth > 0) {
408✔
UNCOV
76
                $shortName .= 'Nested';
18✔
77
            }
UNCOV
78
            $shortName .= 'Input';
408✔
UNCOV
79
        } elseif ($operation instanceof Mutation || $operation instanceof Subscription) {
408✔
UNCOV
80
            if ($depth > 0) {
408✔
UNCOV
81
                $shortName .= 'Nested';
12✔
82
            }
UNCOV
83
            $shortName .= 'Payload';
408✔
84
        }
85

UNCOV
86
        if ('item_query' === $operationName || 'collection_query' === $operationName) {
408✔
87
            // Test if the collection/item has different groups
UNCOV
88
            if ($resourceMetadataCollection->getOperation($operation instanceof CollectionOperationInterface ? 'item_query' : 'collection_query')->getNormalizationContext() !== $operation->getNormalizationContext()) {
408✔
UNCOV
89
                $shortName .= $operation instanceof CollectionOperationInterface ? 'Collection' : 'Item';
408✔
90
            }
91
        }
92

UNCOV
93
        if ($wrapped && ($operation instanceof Mutation || $operation instanceof Subscription)) {
408✔
UNCOV
94
            $shortName .= 'Data';
30✔
95
        }
96

UNCOV
97
        $resourceObjectType = null;
408✔
UNCOV
98
        if (!$this->typesContainer->has($shortName)) {
408✔
UNCOV
99
            $resourceObjectType = $this->getResourceObjectTypeConfiguration($shortName, $resourceMetadataCollection, $operation, $context);
408✔
UNCOV
100
            $this->typesContainer->set($shortName, $resourceObjectType);
408✔
101
        }
102

UNCOV
103
        $resourceObjectType = $resourceObjectType ?? $this->typesContainer->get($shortName);
408✔
UNCOV
104
        if (!($resourceObjectType instanceof ObjectType || $resourceObjectType instanceof NonNull || $resourceObjectType instanceof InputObjectType)) {
408✔
105
            throw new \LogicException(\sprintf('Expected GraphQL type "%s" to be %s.', $shortName, implode('|', [ObjectType::class, NonNull::class, InputObjectType::class])));
×
106
        }
107

UNCOV
108
        $required = $propertyMetadata?->isRequired() ?? true;
408✔
UNCOV
109
        if ($required && $input) {
408✔
UNCOV
110
            $resourceObjectType = GraphQLType::nonNull($resourceObjectType);
408✔
111
        }
112

UNCOV
113
        return $resourceObjectType;
408✔
114
    }
115

116
    /**
117
     * {@inheritdoc}
118
     */
119
    public function getNodeInterface(): InterfaceType
120
    {
UNCOV
121
        if ($this->typesContainer->has('Node')) {
408✔
UNCOV
122
            $nodeInterface = $this->typesContainer->get('Node');
408✔
UNCOV
123
            if (!$nodeInterface instanceof InterfaceType) {
408✔
124
                throw new \LogicException(\sprintf('Expected GraphQL type "Node" to be %s.', InterfaceType::class));
×
125
            }
126

UNCOV
127
            return $nodeInterface;
408✔
128
        }
129

UNCOV
130
        $nodeInterface = new InterfaceType([
408✔
UNCOV
131
            'name' => 'Node',
408✔
UNCOV
132
            'description' => 'A node, according to the Relay specification.',
408✔
UNCOV
133
            'fields' => [
408✔
UNCOV
134
                'id' => [
408✔
UNCOV
135
                    'type' => GraphQLType::nonNull(GraphQLType::id()),
408✔
UNCOV
136
                    'description' => 'The id of this node.',
408✔
UNCOV
137
                ],
408✔
UNCOV
138
            ],
408✔
UNCOV
139
            'resolveType' => function ($value): ?GraphQLType {
408✔
UNCOV
140
                if (!isset($value[ItemNormalizer::ITEM_RESOURCE_CLASS_KEY])) {
3✔
141
                    return null;
×
142
                }
143

UNCOV
144
                $shortName = (new \ReflectionClass($value[ItemNormalizer::ITEM_RESOURCE_CLASS_KEY]))->getShortName();
3✔
145

UNCOV
146
                return $this->typesContainer->has($shortName) ? $this->typesContainer->get($shortName) : null;
3✔
UNCOV
147
            },
408✔
UNCOV
148
        ]);
408✔
149

UNCOV
150
        $this->typesContainer->set('Node', $nodeInterface);
408✔
151

UNCOV
152
        return $nodeInterface;
408✔
153
    }
154

155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function getResourcePaginatedCollectionType(GraphQLType $resourceType, string $resourceClass, Operation $operation): GraphQLType
159
    {
160
        @trigger_error('Using getResourcePaginatedCollectionType method of TypeBuilder is deprecated since API Platform 3.1. Use getPaginatedCollectionType method instead.', \E_USER_DEPRECATED);
×
161

162
        return $this->getPaginatedCollectionType($resourceType, $operation);
×
163
    }
164

165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function getPaginatedCollectionType(GraphQLType $resourceType, Operation $operation): GraphQLType
169
    {
UNCOV
170
        $namedType = GraphQLType::getNamedType($resourceType);
408✔
171
        // graphql-php 15: name() exists
UNCOV
172
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
408✔
UNCOV
173
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
408✔
174

UNCOV
175
        $connectionTypeKey = \sprintf('%s%sConnection', $shortName, ucfirst($paginationType));
408✔
UNCOV
176
        if ($this->typesContainer->has($connectionTypeKey)) {
408✔
UNCOV
177
            return $this->typesContainer->get($connectionTypeKey);
408✔
178
        }
179

UNCOV
180
        $fields = 'cursor' === $paginationType ?
408✔
UNCOV
181
            $this->getCursorBasedPaginationFields($resourceType) :
408✔
UNCOV
182
            $this->getPageBasedPaginationFields($resourceType);
408✔
183

UNCOV
184
        $configuration = [
408✔
UNCOV
185
            'name' => $connectionTypeKey,
408✔
UNCOV
186
            'description' => \sprintf("%s connection for $shortName.", ucfirst($paginationType)),
408✔
UNCOV
187
            'fields' => $fields,
408✔
UNCOV
188
        ];
408✔
189

UNCOV
190
        $resourcePaginatedCollectionType = new ObjectType($configuration);
408✔
UNCOV
191
        $this->typesContainer->set($connectionTypeKey, $resourcePaginatedCollectionType);
408✔
192

UNCOV
193
        return $resourcePaginatedCollectionType;
408✔
194
    }
195

196
    public function getEnumType(Operation $operation): GraphQLType
197
    {
UNCOV
198
        $enumName = $operation->getShortName();
13✔
199

UNCOV
200
        if ($this->typesContainer->has($enumName)) {
13✔
UNCOV
201
            return $this->typesContainer->get($enumName);
10✔
202
        }
203

204
        /** @var FieldsBuilderEnumInterface $fieldsBuilder */
UNCOV
205
        $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
13✔
UNCOV
206
        $enumCases = [];
13✔
UNCOV
207
        $enumCases = $fieldsBuilder->getEnumFields($operation->getClass());
13✔
208

UNCOV
209
        $enumConfig = [
13✔
UNCOV
210
            'name' => $enumName,
13✔
UNCOV
211
            'values' => $enumCases,
13✔
UNCOV
212
        ];
13✔
UNCOV
213
        if ($enumDescription = $operation->getDescription()) {
13✔
214
            $enumConfig['description'] = $enumDescription;
×
215
        }
216

UNCOV
217
        $enumType = new EnumType($enumConfig);
13✔
UNCOV
218
        $this->typesContainer->set($enumName, $enumType);
13✔
219

UNCOV
220
        return $enumType;
13✔
221
    }
222

223
    /**
224
     * {@inheritdoc}
225
     */
226
    public function isCollection(Type $type): bool
227
    {
UNCOV
228
        return $type->isCollection() && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null) && null !== $collectionValueType->getClassName();
408✔
229
    }
230

231
    private function getCursorBasedPaginationFields(GraphQLType $resourceType): array
232
    {
UNCOV
233
        $namedType = GraphQLType::getNamedType($resourceType);
408✔
234
        // graphql-php 15: name() exists
UNCOV
235
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
408✔
236

UNCOV
237
        $edgeObjectTypeConfiguration = [
408✔
UNCOV
238
            'name' => "{$shortName}Edge",
408✔
UNCOV
239
            'description' => "Edge of $shortName.",
408✔
UNCOV
240
            'fields' => [
408✔
UNCOV
241
                'node' => $resourceType,
408✔
UNCOV
242
                'cursor' => GraphQLType::nonNull(GraphQLType::string()),
408✔
UNCOV
243
            ],
408✔
UNCOV
244
        ];
408✔
UNCOV
245
        $edgeObjectType = new ObjectType($edgeObjectTypeConfiguration);
408✔
UNCOV
246
        $this->typesContainer->set("{$shortName}Edge", $edgeObjectType);
408✔
247

UNCOV
248
        $pageInfoObjectTypeConfiguration = [
408✔
UNCOV
249
            'name' => "{$shortName}PageInfo",
408✔
UNCOV
250
            'description' => 'Information about the current page.',
408✔
UNCOV
251
            'fields' => [
408✔
UNCOV
252
                'endCursor' => GraphQLType::string(),
408✔
UNCOV
253
                'startCursor' => GraphQLType::string(),
408✔
UNCOV
254
                'hasNextPage' => GraphQLType::nonNull(GraphQLType::boolean()),
408✔
UNCOV
255
                'hasPreviousPage' => GraphQLType::nonNull(GraphQLType::boolean()),
408✔
UNCOV
256
            ],
408✔
UNCOV
257
        ];
408✔
UNCOV
258
        $pageInfoObjectType = new ObjectType($pageInfoObjectTypeConfiguration);
408✔
UNCOV
259
        $this->typesContainer->set("{$shortName}PageInfo", $pageInfoObjectType);
408✔
260

UNCOV
261
        return [
408✔
UNCOV
262
            'edges' => GraphQLType::listOf($edgeObjectType),
408✔
UNCOV
263
            'pageInfo' => GraphQLType::nonNull($pageInfoObjectType),
408✔
UNCOV
264
            'totalCount' => GraphQLType::nonNull(GraphQLType::int()),
408✔
UNCOV
265
        ];
408✔
266
    }
267

268
    private function getPageBasedPaginationFields(GraphQLType $resourceType): array
269
    {
UNCOV
270
        $namedType = GraphQLType::getNamedType($resourceType);
408✔
271
        // graphql-php 15: name() exists
UNCOV
272
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
408✔
273

UNCOV
274
        $paginationInfoObjectTypeConfiguration = [
408✔
UNCOV
275
            'name' => "{$shortName}PaginationInfo",
408✔
UNCOV
276
            'description' => 'Information about the pagination.',
408✔
UNCOV
277
            'fields' => [
408✔
UNCOV
278
                'itemsPerPage' => GraphQLType::nonNull(GraphQLType::int()),
408✔
UNCOV
279
                'lastPage' => GraphQLType::nonNull(GraphQLType::int()),
408✔
UNCOV
280
                'totalCount' => GraphQLType::nonNull(GraphQLType::int()),
408✔
UNCOV
281
                'hasNextPage' => GraphQLType::nonNull(GraphQLType::boolean()),
408✔
UNCOV
282
            ],
408✔
UNCOV
283
        ];
408✔
UNCOV
284
        $paginationInfoObjectType = new ObjectType($paginationInfoObjectTypeConfiguration);
408✔
UNCOV
285
        $this->typesContainer->set("{$shortName}PaginationInfo", $paginationInfoObjectType);
408✔
286

UNCOV
287
        return [
408✔
UNCOV
288
            'collection' => GraphQLType::listOf($resourceType),
408✔
UNCOV
289
            'paginationInfo' => GraphQLType::nonNull($paginationInfoObjectType),
408✔
UNCOV
290
        ];
408✔
291
    }
292

293
    private function getQueryOperation(ResourceMetadataCollection $resourceMetadataCollection): ?Operation
294
    {
UNCOV
295
        foreach ($resourceMetadataCollection as $resourceMetadata) {
131✔
UNCOV
296
            foreach ($resourceMetadata->getGraphQlOperations() as $operation) {
131✔
297
                // Filter the custom queries.
UNCOV
298
                if ($operation instanceof Query && !$operation->getResolver()) {
131✔
UNCOV
299
                    return $operation;
131✔
300
                }
301
            }
302
        }
303

304
        return null;
×
305
    }
306

307
    private function getResourceObjectTypeConfiguration(string $shortName, ResourceMetadataCollection $resourceMetadataCollection, Operation $operation, array $context = []): InputObjectType|ObjectType
308
    {
UNCOV
309
        $operationName = $operation->getName();
408✔
UNCOV
310
        $resourceClass = $operation->getClass();
408✔
UNCOV
311
        $input = $context['input'];
408✔
UNCOV
312
        $depth = $context['depth'] ?? 0;
408✔
UNCOV
313
        $wrapped = $context['wrapped'] ?? false;
408✔
314

UNCOV
315
        $ioMetadata = $input ? $operation->getInput() : $operation->getOutput();
408✔
UNCOV
316
        if (null !== $ioMetadata && \array_key_exists('class', $ioMetadata) && null !== $ioMetadata['class']) {
408✔
UNCOV
317
            $resourceClass = $ioMetadata['class'];
408✔
318
        }
319

UNCOV
320
        $wrapData = !$wrapped && ($operation instanceof Mutation || $operation instanceof Subscription) && !$input && $depth < 1;
408✔
321

UNCOV
322
        $configuration = [
408✔
UNCOV
323
            'name' => $shortName,
408✔
UNCOV
324
            'description' => $operation->getDescription(),
408✔
UNCOV
325
            'resolveField' => $this->defaultFieldResolver,
408✔
UNCOV
326
            'fields' => function () use ($resourceClass, $operation, $operationName, $resourceMetadataCollection, $input, $wrapData, $depth, $ioMetadata) {
408✔
UNCOV
327
                if ($wrapData) {
390✔
UNCOV
328
                    $queryNormalizationContext = $this->getQueryOperation($resourceMetadataCollection)?->getNormalizationContext() ?? [];
131✔
329

330
                    try {
UNCOV
331
                        $mutationNormalizationContext = $operation instanceof Mutation || $operation instanceof Subscription ? ($resourceMetadataCollection->getOperation($operationName)->getNormalizationContext() ?? []) : [];
131✔
332
                    } catch (OperationNotFoundException) {
×
333
                        $mutationNormalizationContext = [];
×
334
                    }
335
                    // Use a new type for the wrapped object only if there is a specific normalization context for the mutation or the subscription.
336
                    // If not, use the query type in order to ensure the client cache could be used.
UNCOV
337
                    $useWrappedType = $queryNormalizationContext !== $mutationNormalizationContext;
131✔
338

UNCOV
339
                    $wrappedOperationName = $operationName;
131✔
340

UNCOV
341
                    if (!$useWrappedType) {
131✔
UNCOV
342
                        $wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
107✔
343
                    }
344

UNCOV
345
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
131✔
346

UNCOV
347
                    $fields = [
131✔
UNCOV
348
                        lcfirst($wrappedOperation->getShortName()) => $this->getResourceObjectType($resourceMetadataCollection, $wrappedOperation instanceof Operation ? $wrappedOperation : null, null, [
131✔
UNCOV
349
                            'input' => $input,
131✔
UNCOV
350
                            'wrapped' => true,
131✔
UNCOV
351
                            'depth' => $depth,
131✔
UNCOV
352
                        ]),
131✔
UNCOV
353
                    ];
131✔
354

UNCOV
355
                    if ($operation instanceof Subscription) {
131✔
UNCOV
356
                        $fields['clientSubscriptionId'] = GraphQLType::string();
9✔
UNCOV
357
                        if ($operation->getMercure()) {
9✔
UNCOV
358
                            $fields['mercureUrl'] = GraphQLType::string();
9✔
359
                        }
360

UNCOV
361
                        return $fields;
9✔
362
                    }
363

UNCOV
364
                    return $fields + ['clientMutationId' => GraphQLType::string()];
128✔
365
                }
366

UNCOV
367
                $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
390✔
UNCOV
368
                $fields = $fieldsBuilder->getResourceObjectTypeFields($resourceClass, $operation, $input, $depth, $ioMetadata);
390✔
369

UNCOV
370
                if ($input && $operation instanceof Mutation && null !== $mutationArgs = $operation->getArgs()) {
390✔
UNCOV
371
                    return $fieldsBuilder->resolveResourceArgs($mutationArgs, $operation) + ['clientMutationId' => $fields['clientMutationId']];
15✔
372
                }
UNCOV
373
                if ($input && $operation instanceof Mutation && null !== $extraMutationArgs = $operation->getExtraArgs()) {
390✔
UNCOV
374
                    return $fields + $fieldsBuilder->resolveResourceArgs($extraMutationArgs, $operation);
18✔
375
                }
376

UNCOV
377
                return $fields;
390✔
UNCOV
378
            },
408✔
UNCOV
379
            'interfaces' => $wrapData ? [] : [$this->getNodeInterface()],
408✔
UNCOV
380
        ];
408✔
381

UNCOV
382
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
408✔
383
    }
384
}
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