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

api-platform / core / 7970391001

20 Feb 2024 08:19AM UTC coverage: 63.778% (-0.02%) from 63.802%
7970391001

push

github

web-flow
feat(graphql): support nullable embedded relations in GraphQL types (#6100)

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

43 existing lines in 4 files now uncovered.

17092 of 26799 relevant lines covered (63.78%)

29.73 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 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|TypeBuilderEnumInterface|TypeBuilderInterface $typeBuilder, private readonly TypesContainerInterface $typesContainer, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory)
41
    {
42
        if ($typeBuilder instanceof TypeBuilderInterface) {
×
43
            @trigger_error(sprintf('$typeBuilder argument of TypeConverter implementing "%s" is deprecated since API Platform 3.1. It has to implement "%s" instead.', TypeBuilderInterface::class, TypeBuilderEnumInterface::class), \E_USER_DEPRECATED);
×
44
        }
45

NEW
46
        if ($typeBuilder instanceof TypeBuilderEnumInterface) {
×
NEW
47
            @trigger_error(sprintf('$typeBuilder argument of TypeConverter implementing "%s" is deprecated since API Platform 3.3. It has to implement "%s" instead.', TypeBuilderEnumInterface::class, ContextAwareTypeBuilderInterface::class), \E_USER_DEPRECATED);
×
48
        }
49
    }
50

51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function convertType(Type $type, bool $input, Operation $rootOperation, string $resourceClass, string $rootResource, ?string $property, int $depth): GraphQLType|string|null
55
    {
56
        switch ($type->getBuiltinType()) {
×
57
            case Type::BUILTIN_TYPE_BOOL:
58
                return GraphQLType::boolean();
×
59
            case Type::BUILTIN_TYPE_INT:
60
                return GraphQLType::int();
×
61
            case Type::BUILTIN_TYPE_FLOAT:
62
                return GraphQLType::float();
×
63
            case Type::BUILTIN_TYPE_STRING:
64
                return GraphQLType::string();
×
65
            case Type::BUILTIN_TYPE_ARRAY:
66
            case Type::BUILTIN_TYPE_ITERABLE:
67
                if ($resourceType = $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth)) {
×
68
                    return $resourceType;
×
69
                }
70

71
                return 'Iterable';
×
72
            case Type::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 resolveType(string $type): ?GraphQLType
87
    {
88
        try {
89
            $astTypeNode = Parser::parseType($type);
×
90
        } catch (SyntaxError $e) {
×
91
            throw new InvalidArgumentException(sprintf('"%s" is not a valid GraphQL type.', $type), 0, $e);
×
92
        }
93

94
        if ($graphQlType = $this->resolveAstTypeNode($astTypeNode, $type)) {
×
95
            return $graphQlType;
×
96
        }
97

98
        throw new InvalidArgumentException(sprintf('The type "%s" was not resolved.', $type));
×
99
    }
100

101
    private function getResourceType(Type $type, bool $input, Operation $rootOperation, string $rootResource, ?string $property, int $depth): ?GraphQLType
102
    {
103
        if (
104
            $this->typeBuilder->isCollection($type)
×
105
            && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
×
106
        ) {
107
            $resourceClass = $collectionValueType->getClassName();
×
108
        } else {
109
            $resourceClass = $type->getClassName();
×
110
        }
111

112
        if (null === $resourceClass) {
×
113
            return null;
×
114
        }
115

116
        try {
117
            $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
118
        } catch (ResourceClassNotFoundException) {
×
119
            return null;
×
120
        }
121

122
        $hasGraphQl = false;
×
123
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
124
            if (null !== $resourceMetadata->getGraphQlOperations()) {
×
125
                $hasGraphQl = true;
×
126
                break;
×
127
            }
128
        }
129

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

134
        if (!$hasGraphQl) {
×
135
            if (is_a($resourceClass, \BackedEnum::class, true)) {
×
136
                // Remove the condition in API Platform 4.
NEW
137
                if ($this->typeBuilder instanceof TypeBuilderEnumInterface || $this->typeBuilder instanceof ContextAwareTypeBuilderInterface) {
×
138
                    $operation = null;
×
139
                    try {
140
                        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
141
                        $operation = $resourceMetadataCollection->getOperation();
×
142
                    } catch (ResourceClassNotFoundException|OperationNotFoundException) {
×
143
                    }
144
                    /** @var Query $enumOperation */
145
                    $enumOperation = (new Query())
×
146
                        ->withClass($resourceClass)
×
147
                        ->withShortName($operation?->getShortName() ?? (new \ReflectionClass($resourceClass))->getShortName())
×
148
                        ->withDescription($operation?->getDescription());
×
149

150
                    return $this->typeBuilder->getEnumType($enumOperation);
×
151
                }
152
            }
153

154
            return null;
×
155
        }
156

157
        $propertyMetadata = null;
×
158
        if ($property) {
×
159
            $context = [
×
160
                'normalization_groups' => $rootOperation->getNormalizationContext()['groups'] ?? null,
×
161
                'denormalization_groups' => $rootOperation->getDenormalizationContext()['groups'] ?? null,
×
162
            ];
×
163
            $propertyMetadata = $this->propertyMetadataFactory->create($rootResource, $property, $context);
×
164
        }
165

166
        if ($input && $depth > 0 && (!$propertyMetadata || !$propertyMetadata->isWritableLink())) {
×
167
            return GraphQLType::string();
×
168
        }
169

170
        $operationName = $rootOperation->getName();
×
171
        $isCollection = $this->typeBuilder->isCollection($type);
×
172

173
        // We're retrieving the type of a property which is a relation to the root resource.
174
        if ($resourceClass !== $rootResource && $rootOperation instanceof Query) {
×
175
            $operationName = $isCollection ? 'collection_query' : 'item_query';
×
176
        }
177

178
        try {
179
            $operation = $resourceMetadataCollection->getOperation($operationName);
×
180
        } catch (OperationNotFoundException) {
×
181
            $operation = $resourceMetadataCollection->getOperation($isCollection ? 'collection_query' : 'item_query');
×
182
        }
183
        if (!$operation instanceof Operation) {
×
184
            throw new OperationNotFoundException();
×
185
        }
186

NEW
187
        return $this->typeBuilder instanceof ContextAwareTypeBuilderInterface ?
×
NEW
188
            $this->typeBuilder->getResourceObjectType($resourceMetadataCollection, $operation, $propertyMetadata, [
×
NEW
189
                'input' => $input,
×
NEW
190
                'wrapped' => false,
×
NEW
191
                'depth' => $depth,
×
NEW
192
            ]) :
×
NEW
193
            $this->typeBuilder->getResourceObjectType($resourceClass, $resourceMetadataCollection, $operation, $input, false, $depth);
×
194
    }
195

196
    private function resolveAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
197
    {
198
        if ($astTypeNode instanceof NonNullTypeNode) {
×
199
            /** @var NullableType|null $nullableAstTypeNode */
200
            $nullableAstTypeNode = $this->resolveNullableAstTypeNode($astTypeNode->type, $fromType);
×
201

202
            return $nullableAstTypeNode ? GraphQLType::nonNull($nullableAstTypeNode) : null;
×
203
        }
204

205
        return $this->resolveNullableAstTypeNode($astTypeNode, $fromType);
×
206
    }
207

208
    private function resolveNullableAstTypeNode(TypeNode $astTypeNode, string $fromType): ?GraphQLType
209
    {
210
        if ($astTypeNode instanceof ListTypeNode) {
×
211
            /** @var TypeNode $astTypeNodeElement */
212
            $astTypeNodeElement = $astTypeNode->type;
×
213

214
            return GraphQLType::listOf($this->resolveAstTypeNode($astTypeNodeElement, $fromType));
×
215
        }
216

217
        if (!$astTypeNode instanceof NamedTypeNode) {
×
218
            return null;
×
219
        }
220

221
        $typeName = $astTypeNode->name->value;
×
222

223
        return match ($typeName) {
×
224
            GraphQLType::STRING => GraphQLType::string(),
×
225
            GraphQLType::INT => GraphQLType::int(),
×
226
            GraphQLType::BOOLEAN => GraphQLType::boolean(),
×
227
            GraphQLType::FLOAT => GraphQLType::float(),
×
228
            GraphQLType::ID => GraphQLType::id(),
×
229
            default => $this->typesContainer->has($typeName) ? $this->typesContainer->get($typeName) : null,
×
230
        };
×
231
    }
232
}
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