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

api-platform / core / 15904482964

26 Jun 2025 02:22PM UTC coverage: 21.957%. First build
15904482964

Pull #6904

github

web-flow
Merge cea37cac5 into 4ecde01e8
Pull Request #6904: feat(graphql): added support for graphql subscriptions to work for actions

55 of 252 new or added lines in 9 files covered. (21.83%)

11494 of 52347 relevant lines covered (21.96%)

21.6 hits per line

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

75.13
/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 as LegacyType;
34
use Symfony\Component\TypeInfo\Type;
35

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

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

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

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

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

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

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

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

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

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

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

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

114
        return $resourceObjectType;
26✔
115
    }
116

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

128
            return $nodeInterface;
26✔
129
        }
130

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

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

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

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

153
        return $nodeInterface;
26✔
154
    }
155

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

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

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

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

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

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

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

194
        return $resourcePaginatedCollectionType;
12✔
195
    }
196

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

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

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

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

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

221
        return $enumType;
2✔
222
    }
223

224
    /**
225
     * {@inheritdoc}
226
     */
227
    public function isCollection(LegacyType $type): bool
228
    {
229
        trigger_deprecation('api-platform/graphql', '4.2', 'The "%s()" method is deprecated and will be removed.', __METHOD__, self::class);
×
230

231
        return $type->isCollection() && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null) && null !== $collectionValueType->getClassName();
×
232
    }
233

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

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

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

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

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

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

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

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

308
        return null;
×
309
    }
310

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

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

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

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

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

343
                    $wrappedOperationName = $operationName;
2✔
344

345
                    if (!$useWrappedType) {
2✔
346
                        $wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
2✔
347
                    }
348

349
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
2✔
350

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

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

366
                        return $fields;
×
367
                    }
368

369
                    return $fields + ['clientMutationId' => GraphQLType::string()];
2✔
370
                }
371

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

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

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

387
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
26✔
388
    }
389
}
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