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

api-platform / core / 16531587208

25 Jul 2025 09:05PM UTC coverage: 0.0% (-22.1%) from 22.07%
16531587208

Pull #7225

github

web-flow
Merge 23f449a58 into 02a764950
Pull Request #7225: feat: json streamer

0 of 294 new or added lines in 31 files covered. (0.0%)

11514 existing lines in 375 files now uncovered.

0 of 51976 relevant lines covered (0.0%)

0.0 hits per line

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

0.0
/src/GraphQl/Type/TypeConverter.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\Metadata\Exception\InvalidArgumentException;
17
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
18
use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException;
19
use ApiPlatform\Metadata\GraphQl\Operation;
20
use ApiPlatform\Metadata\GraphQl\Query;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Util\TypeHelper;
24
use GraphQL\Error\SyntaxError;
25
use GraphQL\Language\AST\ListTypeNode;
26
use GraphQL\Language\AST\NamedTypeNode;
27
use GraphQL\Language\AST\NonNullTypeNode;
28
use GraphQL\Language\AST\TypeNode;
29
use GraphQL\Language\Parser;
30
use GraphQL\Type\Definition\NullableType;
31
use GraphQL\Type\Definition\Type as GraphQLType;
32
use Symfony\Component\PropertyInfo\Type as LegacyType;
33
use Symfony\Component\TypeInfo\Type;
34
use Symfony\Component\TypeInfo\Type\CollectionType;
35
use Symfony\Component\TypeInfo\Type\ObjectType;
36
use Symfony\Component\TypeInfo\TypeIdentifier;
37

38
/**
39
 * Converts a type to its GraphQL equivalent.
40
 *
41
 * @author Alan Poulain <contact@alanpoulain.eu>
42
 */
43
final class TypeConverter implements TypeConverterInterface
44
{
45
    public function __construct(private readonly ContextAwareTypeBuilderInterface $typeBuilder, private readonly TypesContainerInterface $typesContainer, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory)
46
    {
UNCOV
47
    }
×
48

49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function convertType(LegacyType $type, bool $input, Operation $rootOperation, string $resourceClass, string $rootResource, ?string $property, int $depth): GraphQLType|string|null
53
    {
54
        trigger_deprecation('api-platform/graphql', '4.2', 'The "%s()" method is deprecated, use "%s::convertPhpType()" instead.', __METHOD__, self::class);
×
55

56
        switch ($type->getBuiltinType()) {
×
57
            case LegacyType::BUILTIN_TYPE_BOOL:
×
58
                return GraphQLType::boolean();
×
59
            case LegacyType::BUILTIN_TYPE_INT:
×
60
                return GraphQLType::int();
×
61
            case LegacyType::BUILTIN_TYPE_FLOAT:
×
62
                return GraphQLType::float();
×
63
            case LegacyType::BUILTIN_TYPE_STRING:
×
64
                return GraphQLType::string();
×
65
            case LegacyType::BUILTIN_TYPE_ARRAY:
×
66
            case LegacyType::BUILTIN_TYPE_ITERABLE:
×
67
                if ($resourceType = $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth)) {
×
68
                    return $resourceType;
×
69
                }
70

71
                return 'Iterable';
×
72
            case LegacyType::BUILTIN_TYPE_OBJECT:
×
73
                if (is_a($type->getClassName(), \DateTimeInterface::class, true)) {
×
74
                    return GraphQLType::string();
×
75
                }
76

77
                return $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth);
×
78
            default:
79
                return null;
×
80
        }
81
    }
82

83
    /**
84
     * {@inheritdoc}
85
     */
86
    public function convertPhpType(Type $type, bool $input, Operation $rootOperation, string $resourceClass, string $rootResource, ?string $property, int $depth): GraphQLType|string|null
87
    {
UNCOV
88
        if ($type->isIdentifiedBy(TypeIdentifier::BOOL)) {
×
89
            return GraphQLType::boolean();
×
90
        }
91

UNCOV
92
        if ($type->isIdentifiedBy(TypeIdentifier::INT)) {
×
UNCOV
93
            return GraphQLType::int();
×
94
        }
95

UNCOV
96
        if ($type->isIdentifiedBy(TypeIdentifier::FLOAT)) {
×
97
            return GraphQLType::float();
×
98
        }
99

UNCOV
100
        if ($type->isIdentifiedBy(TypeIdentifier::STRING, \DateTimeInterface::class)) {
×
UNCOV
101
            return GraphQLType::string();
×
102
        }
103

UNCOV
104
        if ($type->isIdentifiedBy(TypeIdentifier::ARRAY, TypeIdentifier::ITERABLE)) {
×
UNCOV
105
            if ($resourceType = $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth)) {
×
UNCOV
106
                return $resourceType;
×
107
            }
108

109
            return 'Iterable';
×
110
        }
111

UNCOV
112
        if ($type->isIdentifiedBy(TypeIdentifier::OBJECT)) {
×
UNCOV
113
            return $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth);
×
114
        }
115

116
        return null;
×
117
    }
118

119
    /**
120
     * {@inheritdoc}
121
     */
122
    public function resolveType(string $type): GraphQLType
123
    {
124
        try {
125
            $astTypeNode = Parser::parseType($type);
×
126
        } catch (SyntaxError $e) {
×
127
            throw new InvalidArgumentException(\sprintf('"%s" is not a valid GraphQL type.', $type), 0, $e);
×
128
        }
129

130
        if ($graphQlType = $this->resolveAstTypeNode($astTypeNode, $type)) {
×
131
            return $graphQlType;
×
132
        }
133

134
        throw new InvalidArgumentException(\sprintf('The type "%s" was not resolved.', $type));
×
135
    }
136

137
    private function getResourceType(Type|LegacyType $type, bool $input, Operation $rootOperation, string $rootResource, ?string $property, int $depth): ?GraphQLType
138
    {
UNCOV
139
        if ($type instanceof Type) {
×
UNCOV
140
            $isCollection = $type->isSatisfiedBy(fn ($t) => $t instanceof CollectionType);
×
141

UNCOV
142
            if ($isCollection) {
×
UNCOV
143
                $type = TypeHelper::getCollectionValueType($type);
×
144
            }
145

146
            /** @var class-string|null $resourceClass */
UNCOV
147
            $resourceClass = null;
×
UNCOV
148
            $typeIsResourceClass = function (Type $type) use (&$resourceClass): bool {
×
UNCOV
149
                return $type instanceof ObjectType && $resourceClass = $type->getClassName();
×
UNCOV
150
            };
×
151

UNCOV
152
            if (!$type->isSatisfiedBy($typeIsResourceClass)) {
×
153
                return null;
×
154
            }
155
        } else {
156
            $isCollection = $this->typeBuilder->isCollection($type);
×
157
            if ($isCollection && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null) {
×
158
                $resourceClass = $collectionValueType->getClassName();
×
159
            } else {
160
                $resourceClass = $type->getClassName();
×
161
            }
162

163
            if (null === $resourceClass) {
×
164
                return null;
×
165
            }
166
        }
167

168
        try {
UNCOV
169
            $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
170
        } catch (ResourceClassNotFoundException) {
×
171
            return null;
×
172
        }
173

UNCOV
174
        $hasGraphQl = false;
×
UNCOV
175
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
UNCOV
176
            if (null !== $resourceMetadata->getGraphQlOperations()) {
×
UNCOV
177
                $hasGraphQl = true;
×
UNCOV
178
                break;
×
179
            }
180
        }
181

UNCOV
182
        if (isset($resourceMetadataCollection[0]) && 'Node' === $resourceMetadataCollection[0]->getShortName()) {
×
183
            throw new \UnexpectedValueException('A "Node" resource cannot be used with GraphQL because the type is already used by the Relay specification.');
×
184
        }
185

UNCOV
186
        if (!$hasGraphQl) {
×
UNCOV
187
            if (is_a($resourceClass, \BackedEnum::class, true)) {
×
UNCOV
188
                $operation = null;
×
189
                try {
UNCOV
190
                    $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
UNCOV
191
                    $operation = $resourceMetadataCollection->getOperation();
×
UNCOV
192
                } catch (ResourceClassNotFoundException|OperationNotFoundException) {
×
193
                }
194
                /** @var Query $enumOperation */
UNCOV
195
                $enumOperation = (new Query())
×
UNCOV
196
                    ->withClass($resourceClass)
×
UNCOV
197
                    ->withShortName($operation?->getShortName() ?? (new \ReflectionClass($resourceClass))->getShortName())
×
UNCOV
198
                    ->withDescription($operation?->getDescription());
×
199

UNCOV
200
                return $this->typeBuilder->getEnumType($enumOperation);
×
201
            }
202

UNCOV
203
            return null;
×
204
        }
205

UNCOV
206
        $propertyMetadata = null;
×
UNCOV
207
        if ($property) {
×
UNCOV
208
            $context = [
×
UNCOV
209
                'normalization_groups' => $rootOperation->getNormalizationContext()['groups'] ?? null,
×
UNCOV
210
                'denormalization_groups' => $rootOperation->getDenormalizationContext()['groups'] ?? null,
×
UNCOV
211
            ];
×
UNCOV
212
            $propertyMetadata = $this->propertyMetadataFactory->create($rootResource, $property, $context);
×
213
        }
214

UNCOV
215
        if ($input && $depth > 0 && (!$propertyMetadata || !$propertyMetadata->isWritableLink())) {
×
UNCOV
216
            return GraphQLType::string();
×
217
        }
218

UNCOV
219
        $operationName = $rootOperation->getName();
×
220

221
        // We're retrieving the type of a property which is a relation to the root resource.
UNCOV
222
        if ($resourceClass !== $rootResource && $rootOperation instanceof Query) {
×
UNCOV
223
            $operationName = $isCollection ? 'collection_query' : 'item_query';
×
224
        }
225

226
        try {
UNCOV
227
            $operation = $resourceMetadataCollection->getOperation($operationName);
×
228
        } catch (OperationNotFoundException) {
×
229
            try {
230
                $operation = $resourceMetadataCollection->getOperation($isCollection ? 'collection_query' : 'item_query');
×
231
            } catch (OperationNotFoundException) {
×
232
                throw new OperationNotFoundException(\sprintf('A GraphQl operation named "%s" should exist on the type "%s" as we reference this type in another query.', $isCollection ? 'collection_query' : 'item_query', $resourceClass));
×
233
            }
234
        }
UNCOV
235
        if (!$operation instanceof Operation) {
×
236
            throw new OperationNotFoundException(\sprintf('A GraphQl operation named "%s" should exist on the type "%s" as we reference this type in another query.', $operationName, $resourceClass));
×
237
        }
238

UNCOV
239
        return $this->typeBuilder->getResourceObjectType($resourceMetadataCollection, $operation, $propertyMetadata, [
×
UNCOV
240
            'input' => $input,
×
UNCOV
241
            'wrapped' => false,
×
UNCOV
242
            'depth' => $depth,
×
UNCOV
243
        ]);
×
244
    }
245

246
    private function resolveAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
247
    {
248
        if ($astTypeNode instanceof NonNullTypeNode) {
×
249
            /** @var (GraphQLType&NullableType)|null $nullableAstTypeNode */
250
            $nullableAstTypeNode = $this->resolveNullableAstTypeNode($astTypeNode->type, $fromType);
×
251

252
            return $nullableAstTypeNode ? GraphQLType::nonNull($nullableAstTypeNode) : null;
×
253
        }
254

255
        return $this->resolveNullableAstTypeNode($astTypeNode, $fromType);
×
256
    }
257

258
    private function resolveNullableAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
259
    {
260
        if ($astTypeNode instanceof ListTypeNode) {
×
261
            /** @var TypeNode $astTypeNodeElement */
262
            $astTypeNodeElement = $astTypeNode->type;
×
263

264
            return GraphQLType::listOf($this->resolveAstTypeNode($astTypeNodeElement, $fromType));
×
265
        }
266

267
        if (!$astTypeNode instanceof NamedTypeNode) {
×
268
            return null;
×
269
        }
270

271
        $typeName = $astTypeNode->name->value;
×
272

273
        return match ($typeName) {
×
274
            GraphQLType::STRING => GraphQLType::string(),
×
275
            GraphQLType::INT => GraphQLType::int(),
×
276
            GraphQLType::BOOLEAN => GraphQLType::boolean(),
×
277
            GraphQLType::FLOAT => GraphQLType::float(),
×
278
            GraphQLType::ID => GraphQLType::id(),
×
279
            default => $this->typesContainer->has($typeName) ? $this->typesContainer->get($typeName) : null,
×
280
        };
×
281
    }
282
}
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