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

api-platform / core / 6981542872

24 Nov 2023 01:48PM UTC coverage: 37.261% (-0.02%) from 37.284%
6981542872

push

github

web-flow
feat(graphql): support enum collection as property (#5955)

Co-authored-by: josef.wagner <josef.wagner@hf-solutions.co>

0 of 40 new or added lines in 6 files covered. (0.0%)

2 existing lines in 2 files now uncovered.

10287 of 27608 relevant lines covered (37.26%)

20.52 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 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
    }
46

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

67
                return 'Iterable';
×
68
            case Type::BUILTIN_TYPE_OBJECT:
69
                if (is_a($type->getClassName(), \DateTimeInterface::class, true)) {
×
70
                    return GraphQLType::string();
×
71
                }
72

NEW
73
                return $this->getResourceType($type, $input, $rootOperation, $rootResource, $property, $depth);
×
74
            default:
75
                return null;
×
76
        }
77
    }
78

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

90
        if ($graphQlType = $this->resolveAstTypeNode($astTypeNode, $type)) {
×
91
            return $graphQlType;
×
92
        }
93

94
        throw new InvalidArgumentException(sprintf('The type "%s" was not resolved.', $type));
×
95
    }
96

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

108
        if (null === $resourceClass) {
×
109
            return null;
×
110
        }
111

112
        try {
113
            $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
114
        } catch (ResourceClassNotFoundException) {
×
115
            return null;
×
116
        }
117

118
        $hasGraphQl = false;
×
119
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
120
            if (null !== $resourceMetadata->getGraphQlOperations()) {
×
121
                $hasGraphQl = true;
×
122
                break;
×
123
            }
124
        }
125

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

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

NEW
146
                    return $this->typeBuilder->getEnumType($enumOperation);
×
147
                }
148
            }
149

UNCOV
150
            return null;
×
151
        }
152

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

162
        if ($input && $depth > 0 && (!$propertyMetadata || !$propertyMetadata->isWritableLink())) {
×
163
            return GraphQLType::string();
×
164
        }
165

166
        $operationName = $rootOperation->getName();
×
167
        $isCollection = $this->typeBuilder->isCollection($type);
×
168

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

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

183
        return $this->typeBuilder->getResourceObjectType($resourceClass, $resourceMetadataCollection, $operation, $input, false, $depth);
×
184
    }
185

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

192
            return $nullableAstTypeNode ? GraphQLType::nonNull($nullableAstTypeNode) : null;
×
193
        }
194

195
        return $this->resolveNullableAstTypeNode($astTypeNode, $fromType);
×
196
    }
197

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

204
            return GraphQLType::listOf($this->resolveAstTypeNode($astTypeNodeElement, $fromType));
×
205
        }
206

207
        if (!$astTypeNode instanceof NamedTypeNode) {
×
208
            return null;
×
209
        }
210

211
        $typeName = $astTypeNode->name->value;
×
212

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