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

api-platform / core / 10510640710

22 Aug 2024 03:02PM UTC coverage: 7.708% (+0.005%) from 7.703%
10510640710

push

github

web-flow
feat(laravel): search filter (#6534)

0 of 103 new or added lines in 11 files covered. (0.0%)

9646 existing lines in 299 files now uncovered.

12490 of 162048 relevant lines covered (7.71%)

22.98 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
    {
UNCOV
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
    {
UNCOV
54
        $shortName = $operation->getShortName();
408✔
UNCOV
55
        $operationName = $operation->getName();
408✔
UNCOV
56
        $input = $context['input'];
408✔
UNCOV
57
        $depth = $context['depth'] ?? 0;
408✔
UNCOV
58
        $wrapped = $context['wrapped'] ?? false;
408✔
59

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

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

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

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

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

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

UNCOV
97
        $resourceObjectType = $resourceObjectType ?? $this->typesContainer->get($shortName);
408✔
UNCOV
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

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

UNCOV
107
        return $resourceObjectType;
408✔
108
    }
109

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

UNCOV
121
            return $nodeInterface;
408✔
122
        }
123

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

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

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

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

UNCOV
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
    {
UNCOV
164
        $namedType = GraphQLType::getNamedType($resourceType);
408✔
165
        // graphql-php 15: name() exists
UNCOV
166
        $shortName = method_exists($namedType, 'name') ? $namedType->name() : $namedType->name;
408✔
UNCOV
167
        $paginationType = $this->pagination->getGraphQlPaginationType($operation);
408✔
168

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

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

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

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

UNCOV
187
        return $resourcePaginatedCollectionType;
408✔
188
    }
189

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

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

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

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

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

UNCOV
214
        return $enumType;
13✔
215
    }
216

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

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

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

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

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

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

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

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

287
    private function getQueryOperation(ResourceMetadataCollection $resourceMetadataCollection): ?Operation
288
    {
UNCOV
289
        foreach ($resourceMetadataCollection as $resourceMetadata) {
131✔
UNCOV
290
            foreach ($resourceMetadata->getGraphQlOperations() as $operation) {
131✔
291
                // Filter the custom queries.
UNCOV
292
                if ($operation instanceof Query && !$operation->getResolver()) {
131✔
UNCOV
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
    {
UNCOV
303
        $operationName = $operation->getName();
408✔
UNCOV
304
        $resourceClass = $operation->getClass();
408✔
UNCOV
305
        $input = $context['input'];
408✔
UNCOV
306
        $depth = $context['depth'] ?? 0;
408✔
UNCOV
307
        $wrapped = $context['wrapped'] ?? false;
408✔
308

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

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

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

324
                    try {
UNCOV
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.
UNCOV
331
                    $useWrappedType = $queryNormalizationContext !== $mutationNormalizationContext;
131✔
332

UNCOV
333
                    $wrappedOperationName = $operationName;
131✔
334

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

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

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

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

UNCOV
355
                        return $fields;
9✔
356
                    }
357

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

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

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

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

UNCOV
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