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

api-platform / core / 10489772975

21 Aug 2024 12:22PM UTC coverage: 7.704%. Remained the same
10489772975

push

github

web-flow
doc: link monorepo to test laravel (#6530)

12476 of 161932 relevant lines covered (7.7%)

23.0 hits per line

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

95.31
/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 readonly ContainerInterface $fieldsBuilderLocator, private readonly Pagination $pagination)
45
    {
46
        $this->defaultFieldResolver = $defaultFieldResolver;
414✔
47
    }
48

49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function getResourceObjectType(ResourceMetadataCollection $resourceMetadataCollection, Operation $operation, ?ApiProperty $propertyMetadata = null, array $context = []): GraphQLType
53
    {
54
        $shortName = $operation->getShortName();
408✔
55
        $operationName = $operation->getName();
408✔
56
        $input = $context['input'];
408✔
57
        $depth = $context['depth'] ?? 0;
408✔
58
        $wrapped = $context['wrapped'] ?? false;
408✔
59

60
        if ($operation instanceof Mutation) {
408✔
61
            $shortName = $operationName.ucfirst($shortName);
408✔
62
        }
63

64
        if ($operation instanceof Subscription) {
408✔
65
            $shortName = $operationName.ucfirst($shortName).'Subscription';
408✔
66
        }
67

68
        if ($input) {
408✔
69
            if ($depth > 0) {
408✔
70
                $shortName .= 'Nested';
18✔
71
            }
72
            $shortName .= 'Input';
408✔
73
        } elseif ($operation instanceof Mutation || $operation instanceof Subscription) {
408✔
74
            if ($depth > 0) {
408✔
75
                $shortName .= 'Nested';
12✔
76
            }
77
            $shortName .= 'Payload';
408✔
78
        }
79

80
        if ('item_query' === $operationName || 'collection_query' === $operationName) {
408✔
81
            // Test if the collection/item has different groups
82
            if ($resourceMetadataCollection->getOperation($operation instanceof CollectionOperationInterface ? 'item_query' : 'collection_query')->getNormalizationContext() !== $operation->getNormalizationContext()) {
408✔
83
                $shortName .= $operation instanceof CollectionOperationInterface ? 'Collection' : 'Item';
408✔
84
            }
85
        }
86

87
        if ($wrapped && ($operation instanceof Mutation || $operation instanceof Subscription)) {
408✔
88
            $shortName .= 'Data';
30✔
89
        }
90

91
        $resourceObjectType = null;
408✔
92
        if (!$this->typesContainer->has($shortName)) {
408✔
93
            $resourceObjectType = $this->getResourceObjectTypeConfiguration($shortName, $resourceMetadataCollection, $operation, $context);
408✔
94
            $this->typesContainer->set($shortName, $resourceObjectType);
408✔
95
        }
96

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

102
        $required = $propertyMetadata?->isRequired() ?? true;
408✔
103
        if ($required && $input) {
408✔
104
            $resourceObjectType = GraphQLType::nonNull($resourceObjectType);
408✔
105
        }
106

107
        return $resourceObjectType;
408✔
108
    }
109

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

121
            return $nodeInterface;
408✔
122
        }
123

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

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

140
                return $this->typesContainer->has($shortName) ? $this->typesContainer->get($shortName) : null;
3✔
141
            },
408✔
142
        ]);
408✔
143

144
        $this->typesContainer->set('Node', $nodeInterface);
408✔
145

146
        return $nodeInterface;
408✔
147
    }
148

149
    /**
150
     * {@inheritdoc}
151
     */
152
    public function getResourcePaginatedCollectionType(GraphQLType $resourceType, string $resourceClass, Operation $operation): GraphQLType
153
    {
154
        @trigger_error('Using getResourcePaginatedCollectionType method of TypeBuilder is deprecated since API Platform 3.1. Use getPaginatedCollectionType method instead.', \E_USER_DEPRECATED);
×
155

156
        return $this->getPaginatedCollectionType($resourceType, $operation);
×
157
    }
158

159
    /**
160
     * {@inheritdoc}
161
     */
162
    public function getPaginatedCollectionType(GraphQLType $resourceType, Operation $operation): GraphQLType
163
    {
164
        $namedType = GraphQLType::getNamedType($resourceType);
408✔
165
        // graphql-php 15: name() exists
166
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
408✔
167
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
408✔
168

169
        $connectionTypeKey = \sprintf('%s%sConnection', $shortName, ucfirst($paginationType));
408✔
170
        if ($this->typesContainer->has($connectionTypeKey)) {
408✔
171
            return $this->typesContainer->get($connectionTypeKey);
408✔
172
        }
173

174
        $fields = 'cursor' === $paginationType ?
408✔
175
            $this->getCursorBasedPaginationFields($resourceType) :
408✔
176
            $this->getPageBasedPaginationFields($resourceType);
408✔
177

178
        $configuration = [
408✔
179
            'name' => $connectionTypeKey,
408✔
180
            'description' => \sprintf("%s connection for $shortName.", ucfirst($paginationType)),
408✔
181
            'fields' => $fields,
408✔
182
        ];
408✔
183

184
        $resourcePaginatedCollectionType = new ObjectType($configuration);
408✔
185
        $this->typesContainer->set($connectionTypeKey, $resourcePaginatedCollectionType);
408✔
186

187
        return $resourcePaginatedCollectionType;
408✔
188
    }
189

190
    public function getEnumType(Operation $operation): GraphQLType
191
    {
192
        $enumName = $operation->getShortName();
13✔
193

194
        if ($this->typesContainer->has($enumName)) {
13✔
195
            return $this->typesContainer->get($enumName);
10✔
196
        }
197

198
        /** @var FieldsBuilderEnumInterface $fieldsBuilder */
199
        $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
13✔
200
        $enumCases = [];
13✔
201
        $enumCases = $fieldsBuilder->getEnumFields($operation->getClass());
13✔
202

203
        $enumConfig = [
13✔
204
            'name' => $enumName,
13✔
205
            'values' => $enumCases,
13✔
206
        ];
13✔
207
        if ($enumDescription = $operation->getDescription()) {
13✔
208
            $enumConfig['description'] = $enumDescription;
×
209
        }
210

211
        $enumType = new EnumType($enumConfig);
13✔
212
        $this->typesContainer->set($enumName, $enumType);
13✔
213

214
        return $enumType;
13✔
215
    }
216

217
    /**
218
     * {@inheritdoc}
219
     */
220
    public function isCollection(Type $type): bool
221
    {
222
        return $type->isCollection() && ($collectionValueType = $type->getCollectionValueTypes()[0] ?? null) && null !== $collectionValueType->getClassName();
408✔
223
    }
224

225
    private function getCursorBasedPaginationFields(GraphQLType $resourceType): array
226
    {
227
        $namedType = GraphQLType::getNamedType($resourceType);
408✔
228
        // graphql-php 15: name() exists
229
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
408✔
230

231
        $edgeObjectTypeConfiguration = [
408✔
232
            'name' => "{$shortName}Edge",
408✔
233
            'description' => "Edge of $shortName.",
408✔
234
            'fields' => [
408✔
235
                'node' => $resourceType,
408✔
236
                'cursor' => GraphQLType::nonNull(GraphQLType::string()),
408✔
237
            ],
408✔
238
        ];
408✔
239
        $edgeObjectType = new ObjectType($edgeObjectTypeConfiguration);
408✔
240
        $this->typesContainer->set("{$shortName}Edge", $edgeObjectType);
408✔
241

242
        $pageInfoObjectTypeConfiguration = [
408✔
243
            'name' => "{$shortName}PageInfo",
408✔
244
            'description' => 'Information about the current page.',
408✔
245
            'fields' => [
408✔
246
                'endCursor' => GraphQLType::string(),
408✔
247
                'startCursor' => GraphQLType::string(),
408✔
248
                'hasNextPage' => GraphQLType::nonNull(GraphQLType::boolean()),
408✔
249
                'hasPreviousPage' => GraphQLType::nonNull(GraphQLType::boolean()),
408✔
250
            ],
408✔
251
        ];
408✔
252
        $pageInfoObjectType = new ObjectType($pageInfoObjectTypeConfiguration);
408✔
253
        $this->typesContainer->set("{$shortName}PageInfo", $pageInfoObjectType);
408✔
254

255
        return [
408✔
256
            'edges' => GraphQLType::listOf($edgeObjectType),
408✔
257
            'pageInfo' => GraphQLType::nonNull($pageInfoObjectType),
408✔
258
            'totalCount' => GraphQLType::nonNull(GraphQLType::int()),
408✔
259
        ];
408✔
260
    }
261

262
    private function getPageBasedPaginationFields(GraphQLType $resourceType): array
263
    {
264
        $namedType = GraphQLType::getNamedType($resourceType);
408✔
265
        // graphql-php 15: name() exists
266
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
408✔
267

268
        $paginationInfoObjectTypeConfiguration = [
408✔
269
            'name' => "{$shortName}PaginationInfo",
408✔
270
            'description' => 'Information about the pagination.',
408✔
271
            'fields' => [
408✔
272
                'itemsPerPage' => GraphQLType::nonNull(GraphQLType::int()),
408✔
273
                'lastPage' => GraphQLType::nonNull(GraphQLType::int()),
408✔
274
                'totalCount' => GraphQLType::nonNull(GraphQLType::int()),
408✔
275
                'hasNextPage' => GraphQLType::nonNull(GraphQLType::boolean()),
408✔
276
            ],
408✔
277
        ];
408✔
278
        $paginationInfoObjectType = new ObjectType($paginationInfoObjectTypeConfiguration);
408✔
279
        $this->typesContainer->set("{$shortName}PaginationInfo", $paginationInfoObjectType);
408✔
280

281
        return [
408✔
282
            'collection' => GraphQLType::listOf($resourceType),
408✔
283
            'paginationInfo' => GraphQLType::nonNull($paginationInfoObjectType),
408✔
284
        ];
408✔
285
    }
286

287
    private function getQueryOperation(ResourceMetadataCollection $resourceMetadataCollection): ?Operation
288
    {
289
        foreach ($resourceMetadataCollection as $resourceMetadata) {
131✔
290
            foreach ($resourceMetadata->getGraphQlOperations() as $operation) {
131✔
291
                // Filter the custom queries.
292
                if ($operation instanceof Query && !$operation->getResolver()) {
131✔
293
                    return $operation;
131✔
294
                }
295
            }
296
        }
297

298
        return null;
×
299
    }
300

301
    private function getResourceObjectTypeConfiguration(string $shortName, ResourceMetadataCollection $resourceMetadataCollection, Operation $operation, array $context = []): InputObjectType|ObjectType
302
    {
303
        $operationName = $operation->getName();
408✔
304
        $resourceClass = $operation->getClass();
408✔
305
        $input = $context['input'];
408✔
306
        $depth = $context['depth'] ?? 0;
408✔
307
        $wrapped = $context['wrapped'] ?? false;
408✔
308

309
        $ioMetadata = $input ? $operation->getInput() : $operation->getOutput();
408✔
310
        if (null !== $ioMetadata && \array_key_exists('class', $ioMetadata) && null !== $ioMetadata['class']) {
408✔
311
            $resourceClass = $ioMetadata['class'];
408✔
312
        }
313

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

316
        $configuration = [
408✔
317
            'name' => $shortName,
408✔
318
            'description' => $operation->getDescription(),
408✔
319
            'resolveField' => $this->defaultFieldResolver,
408✔
320
            'fields' => function () use ($resourceClass, $operation, $operationName, $resourceMetadataCollection, $input, $wrapData, $depth, $ioMetadata) {
408✔
321
                if ($wrapData) {
390✔
322
                    $queryNormalizationContext = $this->getQueryOperation($resourceMetadataCollection)?->getNormalizationContext() ?? [];
131✔
323

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

333
                    $wrappedOperationName = $operationName;
131✔
334

335
                    if (!$useWrappedType) {
131✔
336
                        $wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
107✔
337
                    }
338

339
                    $wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);
131✔
340

341
                    $fields = [
131✔
342
                        lcfirst($wrappedOperation->getShortName()) => $this->getResourceObjectType($resourceMetadataCollection, $wrappedOperation instanceof Operation ? $wrappedOperation : null, null, [
131✔
343
                            'input' => $input,
131✔
344
                            'wrapped' => true,
131✔
345
                            'depth' => $depth,
131✔
346
                        ]),
131✔
347
                    ];
131✔
348

349
                    if ($operation instanceof Subscription) {
131✔
350
                        $fields['clientSubscriptionId'] = GraphQLType::string();
9✔
351
                        if ($operation->getMercure()) {
9✔
352
                            $fields['mercureUrl'] = GraphQLType::string();
9✔
353
                        }
354

355
                        return $fields;
9✔
356
                    }
357

358
                    return $fields + ['clientMutationId' => GraphQLType::string()];
128✔
359
                }
360

361
                $fieldsBuilder = $this->fieldsBuilderLocator->get('api_platform.graphql.fields_builder');
390✔
362
                $fields = $fieldsBuilder->getResourceObjectTypeFields($resourceClass, $operation, $input, $depth, $ioMetadata);
390✔
363

364
                if ($input && $operation instanceof Mutation && null !== $mutationArgs = $operation->getArgs()) {
390✔
365
                    return $fieldsBuilder->resolveResourceArgs($mutationArgs, $operation) + ['clientMutationId' => $fields['clientMutationId']];
15✔
366
                }
367
                if ($input && $operation instanceof Mutation && null !== $extraMutationArgs = $operation->getExtraArgs()) {
390✔
368
                    return $fields + $fieldsBuilder->resolveResourceArgs($extraMutationArgs, $operation);
18✔
369
                }
370

371
                return $fields;
390✔
372
            },
408✔
373
            'interfaces' => $wrapData ? [] : [$this->getNodeInterface()],
408✔
374
        ];
408✔
375

376
        return $input ? new InputObjectType($configuration) : new ObjectType($configuration);
408✔
377
    }
378
}
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