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

api-platform / core / 10814494863

11 Sep 2024 03:11PM UTC coverage: 7.008% (-0.7%) from 7.679%
10814494863

push

github

web-flow
fix(state): remove resource_class change (#6607)

11516 of 164321 relevant lines covered (7.01%)

22.85 hits per line

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

90.53
/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
    }
414✔
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()) {
408✔
50
            case Type::BUILTIN_TYPE_BOOL:
408✔
51
                return GraphQLType::boolean();
408✔
52
            case Type::BUILTIN_TYPE_INT:
408✔
53
                return GraphQLType::int();
408✔
54
            case Type::BUILTIN_TYPE_FLOAT:
408✔
55
                return GraphQLType::float();
408✔
56
            case Type::BUILTIN_TYPE_STRING:
408✔
57
                return GraphQLType::string();
408✔
58
            case Type::BUILTIN_TYPE_ARRAY:
408✔
59
            case Type::BUILTIN_TYPE_ITERABLE:
408✔
60
                if ($resourceType = $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth)) {
323✔
61
                    return $resourceType;
30✔
62
                }
63

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

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

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

87
        if ($graphQlType = $this->resolveAstTypeNode($astTypeNode, $type)) {
408✔
88
            return $graphQlType;
408✔
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)
408✔
98
            && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
408✔
99
        ) {
100
            $resourceClass = $collectionValueType->getClassName();
408✔
101
        } else {
102
            $resourceClass = $type->getClassName();
408✔
103
        }
104

105
        if (null === $resourceClass) {
408✔
106
            return null;
311✔
107
        }
108

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

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

123
        if (isset($resourceMetadataCollection[0]) && 'Node' === $resourceMetadataCollection[0]->getShortName()) {
408✔
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) {
408✔
128
            if (is_a($resourceClass, \BackedEnum::class, true)) {
86✔
129
                $operation = null;
13✔
130
                try {
131
                    $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
13✔
132
                    $operation = $resourceMetadataCollection->getOperation();
13✔
133
                } catch (ResourceClassNotFoundException|OperationNotFoundException) {
13✔
134
                }
135
                /** @var Query $enumOperation */
136
                $enumOperation = (new Query())
13✔
137
                    ->withClass($resourceClass)
13✔
138
                    ->withShortName($operation?->getShortName() ?? (new \ReflectionClass($resourceClass))->getShortName())
13✔
139
                    ->withDescription($operation?->getDescription());
13✔
140

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

144
            return null;
86✔
145
        }
146

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

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

160
        $operationName = $rootOperation->getName();
408✔
161
        $isCollection = $this->typeBuilder->isCollection($type);
408✔
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) {
408✔
165
            $operationName = $isCollection ? 'collection_query' : 'item_query';
264✔
166
        }
167

168
        try {
169
            $operation = $resourceMetadataCollection->getOperation($operationName);
408✔
170
        } catch (OperationNotFoundException) {
15✔
171
            $operation = $resourceMetadataCollection->getOperation($isCollection ? 'collection_query' : 'item_query');
15✔
172
        }
173
        if (!$operation instanceof Operation) {
408✔
174
            throw new OperationNotFoundException();
×
175
        }
176

177
        return $this->typeBuilder->getResourceObjectType($resourceMetadataCollection, $operation, $propertyMetadata, [
408✔
178
            'input' => $input,
408✔
179
            'wrapped' => false,
408✔
180
            'depth' => $depth,
408✔
181
        ]);
408✔
182
    }
183

184
    private function resolveAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
185
    {
186
        if ($astTypeNode instanceof NonNullTypeNode) {
408✔
187
            /** @var NullableType|null $nullableAstTypeNode */
188
            $nullableAstTypeNode = $this->resolveNullableAstTypeNode($astTypeNode->type, $fromType);
408✔
189

190
            return $nullableAstTypeNode ? GraphQLType::nonNull($nullableAstTypeNode) : null;
408✔
191
        }
192

193
        return $this->resolveNullableAstTypeNode($astTypeNode, $fromType);
408✔
194
    }
195

196
    private function resolveNullableAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
197
    {
198
        if ($astTypeNode instanceof ListTypeNode) {
408✔
199
            /** @var TypeNode $astTypeNodeElement */
200
            $astTypeNodeElement = $astTypeNode->type;
408✔
201

202
            return GraphQLType::listOf($this->resolveAstTypeNode($astTypeNodeElement, $fromType));
408✔
203
        }
204

205
        if (!$astTypeNode instanceof NamedTypeNode) {
408✔
206
            return null;
×
207
        }
208

209
        $typeName = $astTypeNode->name->value;
408✔
210

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