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

api-platform / core / 14664641376

25 Apr 2025 12:30PM UTC coverage: 7.02%. First build
14664641376

Pull #6904

github

web-flow
Merge decfc5b24 into 7c796de0d
Pull Request #6904: feat(graphql): added support for graphql subscriptions to work for actions

55 of 192 new or added lines in 9 files covered. (28.65%)

11165 of 159046 relevant lines covered (7.02%)

6.23 hits per line

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

76.02
/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
    {
46
        $this->fieldsBuilderLocator = $fieldsBuilderLocator;
26✔
47
        $this->defaultFieldResolver = $defaultFieldResolver;
26✔
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
    {
60
        $shortName = $operation->getShortName();
26✔
61
        $operationName = $operation->getName();
26✔
62
        $input = $context['input'];
26✔
63
        $depth = $context['depth'] ?? 0;
26✔
64
        $wrapped = $context['wrapped'] ?? false;
26✔
65

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

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

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

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

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

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

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

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

113
        return $resourceObjectType;
26✔
114
    }
115

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

127
            return $nodeInterface;
26✔
128
        }
129

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

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

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

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

152
        return $nodeInterface;
26✔
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
    {
170
        $namedType = GraphQLType::getNamedType($resourceType);
12✔
171
        // graphql-php 15: name() exists
172
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
12✔
173
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
12✔
174

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

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

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

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

193
        return $resourcePaginatedCollectionType;
12✔
194
    }
195

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

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

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

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

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

220
        return $enumType;
2✔
221
    }
222

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

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

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

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

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

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

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

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

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

305
        return null;
×
306
    }
307

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

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

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

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

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

340
                    $wrappedOperationName = $operationName;
2✔
341

342
                    if (!$useWrappedType) {
2✔
343
                        $wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
2✔
344
                    }
345

346
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
2✔
347

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

356
                    if ($operation instanceof Subscription) {
2✔
357
                        $fields['clientSubscriptionId'] = GraphQLType::string();
×
NEW
358
                        $fields['isCollection'] = GraphQLType::boolean();
×
359
                        if ($operation->getMercure()) {
×
360
                            $fields['mercureUrl'] = GraphQLType::string();
×
361
                        }
362

363
                        return $fields;
×
364
                    }
365

366
                    return $fields + ['clientMutationId' => GraphQLType::string()];
2✔
367
                }
368

369
                $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
26✔
370
                $fields = $fieldsBuilder->getResourceObjectTypeFields($resourceClass, $operation, $input, $depth, $ioMetadata);
26✔
371

372
                if ($input && $operation instanceof Mutation && null !== $mutationArgs = $operation->getArgs()) {
26✔
373
                    return $fieldsBuilder->resolveResourceArgs($mutationArgs, $operation) + ['clientMutationId' => $fields['clientMutationId']];
×
374
                }
375
                if ($input && $operation instanceof Mutation && null !== $extraMutationArgs = $operation->getExtraArgs()) {
26✔
376
                    return $fields + $fieldsBuilder->resolveResourceArgs($extraMutationArgs, $operation);
×
377
                }
378

379
                return $fields;
26✔
380
            },
26✔
381
            'interfaces' => $wrapData ? [] : [$this->getNodeInterface()],
26✔
382
        ];
26✔
383

384
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
26✔
385
    }
386
}
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