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

api-platform / core / 14635100171

24 Apr 2025 06:39AM UTC coverage: 8.271% (+0.02%) from 8.252%
14635100171

Pull #6904

github

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

0 of 73 new or added lines in 3 files covered. (0.0%)

1999 existing lines in 144 files now uncovered.

13129 of 158728 relevant lines covered (8.27%)

13.6 hits per line

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

88.66
/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 GraphQL\Error\SyntaxError;
24
use GraphQL\Language\AST\ListTypeNode;
25
use GraphQL\Language\AST\NamedTypeNode;
26
use GraphQL\Language\AST\NonNullTypeNode;
27
use GraphQL\Language\AST\TypeNode;
28
use GraphQL\Language\Parser;
29
use GraphQL\Type\Definition\NullableType;
30
use GraphQL\Type\Definition\Type as GraphQLType;
31
use Symfony\Component\PropertyInfo\Type;
32

33
/**
34
 * Converts a type to its GraphQL equivalent.
35
 *
36
 * @author Alan Poulain <contact@alanpoulain.eu>
37
 */
38
final class TypeConverter implements TypeConverterInterface
39
{
40
    public function __construct(private readonly ContextAwareTypeBuilderInterface $typeBuilder, private readonly TypesContainerInterface $typesContainer, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory)
41
    {
42
    }
161✔
43

44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function convertType(Type $type, bool $input, Operation $rootOperation, string $resourceClass, string $rootResource, ?string $property, int $depth): GraphQLType|string|null
48
    {
49
        switch ($type->getBuiltinType()) {
159✔
50
            case Type::BUILTIN_TYPE_BOOL:
133✔
UNCOV
51
                return GraphQLType::boolean();
133✔
52
            case Type::BUILTIN_TYPE_INT:
133✔
53
                return GraphQLType::int();
153✔
54
            case Type::BUILTIN_TYPE_FLOAT:
133✔
UNCOV
55
                return GraphQLType::float();
133✔
56
            case Type::BUILTIN_TYPE_STRING:
133✔
57
                return GraphQLType::string();
153✔
58
            case Type::BUILTIN_TYPE_ARRAY:
133✔
59
            case Type::BUILTIN_TYPE_ITERABLE:
133✔
60
                if ($resourceType = $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth)) {
135✔
61
                    return $resourceType;
10✔
62
                }
63

UNCOV
64
                return 'Iterable';
133✔
65
            case Type::BUILTIN_TYPE_OBJECT:
133✔
66
                if (is_a($type->getClassName(), \DateTimeInterface::class, true)) {
159✔
67
                    return GraphQLType::string();
135✔
68
                }
69

70
                return $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth);
159✔
71
            default:
72
                return null;
×
73
        }
74
    }
75

76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function resolveType(string $type): ?GraphQLType
80
    {
81
        try {
UNCOV
82
            $astTypeNode = Parser::parseType($type);
133✔
83
        } catch (SyntaxError $e) {
×
84
            throw new InvalidArgumentException(\sprintf('"%s" is not a valid GraphQL type.', $type), 0, $e);
×
85
        }
86

UNCOV
87
        if ($graphQlType = $this->resolveAstTypeNode($astTypeNode, $type)) {
133✔
UNCOV
88
            return $graphQlType;
133✔
89
        }
90

91
        throw new InvalidArgumentException(\sprintf('The type "%s" was not resolved.', $type));
×
92
    }
93

94
    private function getResourceType(Type $type, bool $input, Operation $rootOperation, string $rootResource, ?string $property, int $depth): ?GraphQLType
95
    {
96
        if (
97
            $this->typeBuilder->isCollection($type)
159✔
98
            && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
159✔
99
        ) {
100
            $resourceClass = $collectionValueType->getClassName();
159✔
101
        } else {
102
            $resourceClass = $type->getClassName();
157✔
103
        }
104

105
        if (null === $resourceClass) {
159✔
UNCOV
106
            return null;
133✔
107
        }
108

109
        try {
110
            $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
159✔
111
        } catch (ResourceClassNotFoundException) {
×
112
            return null;
×
113
        }
114

115
        $hasGraphQl = false;
159✔
116
        foreach ($resourceMetadataCollection as $resourceMetadata) {
159✔
117
            if (null !== $resourceMetadata->getGraphQlOperations()) {
159✔
118
                $hasGraphQl = true;
159✔
119
                break;
159✔
120
            }
121
        }
122

123
        if (isset($resourceMetadataCollection[0]) && 'Node' === $resourceMetadataCollection[0]->getShortName()) {
159✔
124
            throw new \UnexpectedValueException('A "Node" resource cannot be used with GraphQL because the type is already used by the Relay specification.');
×
125
        }
126

127
        if (!$hasGraphQl) {
159✔
128
            if (is_a($resourceClass, \BackedEnum::class, true)) {
32✔
129
                $operation = null;
6✔
130
                try {
131
                    $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
6✔
132
                    $operation = $resourceMetadataCollection->getOperation();
6✔
133
                } catch (ResourceClassNotFoundException|OperationNotFoundException) {
6✔
134
                }
135
                /** @var Query $enumOperation */
136
                $enumOperation = (new Query())
6✔
137
                    ->withClass($resourceClass)
6✔
138
                    ->withShortName($operation?->getShortName() ?? (new \ReflectionClass($resourceClass))->getShortName())
6✔
139
                    ->withDescription($operation?->getDescription());
6✔
140

141
                return $this->typeBuilder->getEnumType($enumOperation);
6✔
142
            }
143

144
            return null;
32✔
145
        }
146

147
        $propertyMetadata = null;
159✔
148
        if ($property) {
159✔
149
            $context = [
99✔
150
                'normalization_groups' => $rootOperation->getNormalizationContext()['groups'] ?? null,
99✔
151
                'denormalization_groups' => $rootOperation->getDenormalizationContext()['groups'] ?? null,
99✔
152
            ];
99✔
153
            $propertyMetadata = $this->propertyMetadataFactory->create($rootResource, $property, $context);
99✔
154
        }
155

156
        if ($input && $depth > 0 && (!$propertyMetadata || !$propertyMetadata->isWritableLink())) {
159✔
157
            return GraphQLType::string();
23✔
158
        }
159

160
        $operationName = $rootOperation->getName();
159✔
161
        $isCollection = $this->typeBuilder->isCollection($type);
159✔
162

163
        // We're retrieving the type of a property which is a relation to the root resource.
164
        if ($resourceClass !== $rootResource && $rootOperation instanceof Query) {
159✔
165
            $operationName = $isCollection ? 'collection_query' : 'item_query';
94✔
166
        }
167

168
        try {
169
            $operation = $resourceMetadataCollection->getOperation($operationName);
159✔
UNCOV
170
        } catch (OperationNotFoundException) {
4✔
171
            try {
UNCOV
172
                $operation = $resourceMetadataCollection->getOperation($isCollection ? 'collection_query' : 'item_query');
4✔
173
            } catch (OperationNotFoundException) {
×
174
                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));
×
175
            }
176
        }
177
        if (!$operation instanceof Operation) {
159✔
178
            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));
×
179
        }
180

181
        return $this->typeBuilder->getResourceObjectType($resourceMetadataCollection, $operation, $propertyMetadata, [
159✔
182
            'input' => $input,
159✔
183
            'wrapped' => false,
159✔
184
            'depth' => $depth,
159✔
185
        ]);
159✔
186
    }
187

188
    private function resolveAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
189
    {
UNCOV
190
        if ($astTypeNode instanceof NonNullTypeNode) {
133✔
191
            /** @var NullableType|null $nullableAstTypeNode */
UNCOV
192
            $nullableAstTypeNode = $this->resolveNullableAstTypeNode($astTypeNode->type, $fromType);
133✔
193

UNCOV
194
            return $nullableAstTypeNode ? GraphQLType::nonNull($nullableAstTypeNode) : null;
133✔
195
        }
196

UNCOV
197
        return $this->resolveNullableAstTypeNode($astTypeNode, $fromType);
133✔
198
    }
199

200
    private function resolveNullableAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
201
    {
UNCOV
202
        if ($astTypeNode instanceof ListTypeNode) {
133✔
203
            /** @var TypeNode $astTypeNodeElement */
UNCOV
204
            $astTypeNodeElement = $astTypeNode->type;
133✔
205

UNCOV
206
            return GraphQLType::listOf($this->resolveAstTypeNode($astTypeNodeElement, $fromType));
133✔
207
        }
208

UNCOV
209
        if (!$astTypeNode instanceof NamedTypeNode) {
133✔
210
            return null;
×
211
        }
212

UNCOV
213
        $typeName = $astTypeNode->name->value;
133✔
214

UNCOV
215
        return match ($typeName) {
133✔
UNCOV
216
            GraphQLType::STRING => GraphQLType::string(),
133✔
UNCOV
217
            GraphQLType::INT => GraphQLType::int(),
133✔
UNCOV
218
            GraphQLType::BOOLEAN => GraphQLType::boolean(),
133✔
UNCOV
219
            GraphQLType::FLOAT => GraphQLType::float(),
133✔
UNCOV
220
            GraphQLType::ID => GraphQLType::id(),
133✔
UNCOV
221
            default => $this->typesContainer->has($typeName) ? $this->typesContainer->get($typeName) : null,
133✔
UNCOV
222
        };
133✔
223
    }
224
}
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