Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Pull Request — master (#731)
by Vincent
23:11
created

inputAnnotationToGQLConfiguration()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 7
rs 10
ccs 2
cts 2
cp 1
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Overblog\GraphQLBundle\Config\Parser;
6
7
use Doctrine\Common\Annotations\AnnotationException;
8
use Doctrine\ORM\Mapping\Column;
9
use Doctrine\ORM\Mapping\JoinColumn;
10
use Doctrine\ORM\Mapping\ManyToMany;
11
use Doctrine\ORM\Mapping\ManyToOne;
12
use Doctrine\ORM\Mapping\OneToMany;
13
use Doctrine\ORM\Mapping\OneToOne;
14
use Exception;
15
use Overblog\GraphQLBundle\Annotation as GQL;
16
use Overblog\GraphQLBundle\Config\Parser\Annotation\GraphClass;
17
use Overblog\GraphQLBundle\Relay\Connection\ConnectionInterface;
18
use Overblog\GraphQLBundle\Relay\Connection\EdgeInterface;
19
use ReflectionException;
20
use ReflectionMethod;
21
use ReflectionNamedType;
22
use ReflectionProperty;
23
use Reflector;
24
use RuntimeException;
25
use SplFileInfo;
26
use Symfony\Component\Config\Resource\FileResource;
27
use Symfony\Component\DependencyInjection\ContainerBuilder;
28
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
29
use function array_filter;
30
use function array_keys;
31
use function array_map;
32
use function array_unshift;
33
use function current;
34
use function file_get_contents;
35
use function get_class;
36
use function implode;
37
use function in_array;
38
use function is_array;
39
use function is_string;
40
use function preg_match;
41
use function sprintf;
42
use function str_replace;
43
use function strlen;
44
use function strpos;
45
use function substr;
46
use function trim;
47
48
class AnnotationParser implements PreParserInterface
49
{
50
    private static array $classesMap = [];
51
    private static array $providers = [];
52
    private static array $doctrineMapping = [];
53
    private static array $graphClassCache = [];
54
55
    private const GQL_SCALAR = 'scalar';
56
    private const GQL_ENUM = 'enum';
57
    private const GQL_TYPE = 'type';
58
    private const GQL_INPUT = 'input';
59
    private const GQL_UNION = 'union';
60
    private const GQL_INTERFACE = 'interface';
61
62
    /**
63
     * @see https://facebook.github.io/graphql/draft/#sec-Input-and-Output-Types
64
     */
65
    private const VALID_INPUT_TYPES = [self::GQL_SCALAR, self::GQL_ENUM, self::GQL_INPUT];
66
    private const VALID_OUTPUT_TYPES = [self::GQL_SCALAR, self::GQL_TYPE, self::GQL_INTERFACE, self::GQL_UNION, self::GQL_ENUM];
67
68
    /**
69
     * {@inheritdoc}
70
     *
71
     * @throws InvalidArgumentException
72
     * @throws ReflectionException
73
     */
74 25
    public static function preParse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): void
75
    {
76 25
        $container->setParameter('overblog_graphql_types.classes_map', self::processFile($file, $container, $configs, true));
77 25
    }
78
79
    /**
80
     * @throws InvalidArgumentException
81
     * @throws ReflectionException
82
     */
83 25
    public static function parse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): array
84
    {
85 25
        return self::processFile($file, $container, $configs, false);
86
    }
87
88
    /**
89
     * @internal
90
     */
91 63
    public static function reset(): void
92
    {
93 63
        self::$classesMap = [];
94 63
        self::$providers = [];
95 63
        self::$graphClassCache = [];
96 63
    }
97
98
    /**
99
     * Process a file.
100
     *
101
     * @throws InvalidArgumentException|ReflectionException|AnnotationException
102
     */
103 25
    private static function processFile(SplFileInfo $file, ContainerBuilder $container, array $configs, bool $preProcess): array
104
    {
105 25
        self::$doctrineMapping = $configs['doctrine']['types_mapping'];
106 25
        $container->addResource(new FileResource($file->getRealPath()));
107
108
        try {
109 25
            $className = $file->getBasename('.php');
110 25
            if (preg_match('#namespace (.+);#', file_get_contents($file->getRealPath()), $matches)) {
111 25
                $className = trim($matches[1]).'\\'.$className;
112
            }
113
114 25
            $gqlTypes = [];
115 25
            $graphClass = self::getGraphClass($className);
116
117 25
            foreach ($graphClass->getAnnotations() as $classAnnotation) {
118 25
                $gqlTypes = self::classAnnotationsToGQLConfiguration(
119 25
                    $graphClass,
120
                    $classAnnotation,
121
                    $configs,
122
                    $gqlTypes,
123
                    $preProcess
124
                );
125
            }
126
127 25
            return $preProcess ? self::$classesMap : $gqlTypes;
128 10
        } catch (\InvalidArgumentException $e) {
129 10
            throw new InvalidArgumentException(sprintf('Failed to parse GraphQL annotations from file "%s".', $file), $e->getCode(), $e);
130
        }
131
    }
132
133 25
    private static function classAnnotationsToGQLConfiguration(
134
        GraphClass $graphClass,
135
        object $classAnnotation,
136
        array $configs,
137
        array $gqlTypes,
138
        bool $preProcess
139
    ): array {
140 25
        $gqlConfiguration = $gqlType = $gqlName = null;
141
142
        switch (true) {
143 25
            case $classAnnotation instanceof GQL\Type:
144 25
                $gqlType = self::GQL_TYPE;
145 25
                $gqlName = $classAnnotation->name ?? $graphClass->getShortName();
146 25
                if (!$preProcess) {
147 25
                    $gqlConfiguration = self::typeAnnotationToGQLConfiguration($graphClass, $classAnnotation, $gqlName, $configs);
148
149 25
                    if ($classAnnotation instanceof GQL\Relay\Connection) {
150 24
                        if (!$graphClass->implementsInterface(ConnectionInterface::class)) {
151
                            throw new InvalidArgumentException(sprintf('The annotation @Connection on class "%s" can only be used on class implementing the ConnectionInterface.', $graphClass->getName()));
152
                        }
153
154 24
                        if (!(isset($classAnnotation->edge) xor isset($classAnnotation->node))) {
155
                            throw new InvalidArgumentException(sprintf('The annotation @Connection on class "%s" is invalid. You must define either the "edge" OR the "node" attribute, but not both.', $graphClass->getName()));
156
                        }
157
158 24
                        $edgeType = $classAnnotation->edge ?? false;
159 24
                        if (!$edgeType) {
160 24
                            $edgeType = $gqlName.'Edge';
161 24
                            $gqlTypes[$edgeType] = [
162 24
                                'type' => 'object',
163
                                'config' => [
164
                                    'builders' => [
165 24
                                        ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classAnnotation->node]],
166
                                    ],
167
                                ],
168
                            ];
169
                        }
170
171 24
                        if (!isset($gqlConfiguration['config']['builders'])) {
172 24
                            $gqlConfiguration['config']['builders'] = [];
173
                        }
174
175 24
                        array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-connection', 'builderConfig' => ['edgeType' => $edgeType]]);
176
                    }
177
                }
178 25
                break;
179
180 24
            case $classAnnotation instanceof GQL\Input:
181 24
                $gqlType = self::GQL_INPUT;
182 24
                $gqlName = $classAnnotation->name ?? self::suffixName($graphClass->getShortName(), 'Input');
183 24
                if (!$preProcess) {
184 24
                    $gqlConfiguration = self::inputAnnotationToGQLConfiguration($graphClass, $classAnnotation);
185
                }
186 24
                break;
187
188 24
            case $classAnnotation instanceof GQL\Scalar:
189 24
                $gqlType = self::GQL_SCALAR;
190 24
                if (!$preProcess) {
191 24
                    $gqlConfiguration = self::scalarAnnotationToGQLConfiguration($graphClass, $classAnnotation);
192
                }
193 24
                break;
194
195 24
            case $classAnnotation instanceof GQL\Enum:
196 24
                $gqlType = self::GQL_ENUM;
197 24
                if (!$preProcess) {
198 24
                    $gqlConfiguration = self::enumAnnotationToGQLConfiguration($graphClass, $classAnnotation);
199
                }
200 24
                break;
201
202 24
            case $classAnnotation instanceof GQL\Union:
203 24
                $gqlType = self::GQL_UNION;
204 24
                if (!$preProcess) {
205 24
                    $gqlConfiguration = self::unionAnnotationToGQLConfiguration($graphClass, $classAnnotation);
206
                }
207 24
                break;
208
209 24
            case $classAnnotation instanceof GQL\TypeInterface:
210 24
                $gqlType = self::GQL_INTERFACE;
211 24
                if (!$preProcess) {
212 24
                    $gqlConfiguration = self::typeInterfaceAnnotationToGQLConfiguration($graphClass, $classAnnotation);
213
                }
214 24
                break;
215
216 24
            case $classAnnotation instanceof GQL\Provider:
217 24
                if ($preProcess) {
218 24
                    self::$providers[] = ['metadata' => $graphClass, 'annotation' => $classAnnotation];
219
                }
220
221 24
                return [];
222
        }
223
224 25
        if (null !== $gqlType) {
225 25
            if (!$gqlName) {
226 24
                $gqlName = isset($classAnnotation->name) ? $classAnnotation->name : $graphClass->getShortName();
227
            }
228
229 25
            if ($preProcess) {
230 25
                if (isset(self::$classesMap[$gqlName])) {
231 1
                    throw new InvalidArgumentException(sprintf('The GraphQL type "%s" has already been registered in class "%s"', $gqlName, self::$classesMap[$gqlName]['class']));
232
                }
233 25
                self::$classesMap[$gqlName] = ['type' => $gqlType, 'class' => $graphClass->getName()];
234
            } else {
235 25
                $gqlTypes = [$gqlName => $gqlConfiguration] + $gqlTypes;
236
            }
237
        }
238
239 25
        return $gqlTypes;
240
    }
241
242
    /**
243
     * @throws ReflectionException
244
     */
245 25
    private static function getGraphClass(string $className): GraphClass
246
    {
247 25
        self::$graphClassCache[$className] ??= new GraphClass($className);
248
249 25
        return self::$graphClassCache[$className];
250
    }
251
252 25
    private static function typeAnnotationToGQLConfiguration(
253
        GraphClass $graphClass,
254
        GQL\Type $classAnnotation,
255
        string $gqlName,
256
        array $configs
257
    ): array {
258 25
        $isMutation = $isDefault = $isRoot = false;
259 25
        if (isset($configs['definitions']['schema'])) {
260 24
            $defaultSchemaName = isset($configs['definitions']['schema']['default']) ? 'default' : array_key_first($configs['definitions']['schema']);
261 24
            foreach ($configs['definitions']['schema'] as $schemaName => $schema) {
262 24
                $schemaQuery = $schema['query'] ?? null;
263 24
                $schemaMutation = $schema['mutation'] ?? null;
264
265 24
                if ($gqlName === $schemaQuery) {
266 24
                    $isRoot = true;
267 24
                    if ($defaultSchemaName === $schemaName) {
268 24
                        $isDefault = true;
269
                    }
270 24
                } elseif ($gqlName === $schemaMutation) {
271 24
                    $isMutation = true;
272 24
                    $isRoot = true;
273 24
                    if ($defaultSchemaName === $schemaName) {
274 24
                        $isDefault = true;
275
                    }
276
                }
277
            }
278
        }
279
280 25
        $currentValue = $isRoot ? sprintf("service('%s')", self::formatNamespaceForExpression($graphClass->getName())) : 'value';
281
282 25
        $gqlConfiguration = self::graphQLTypeConfigFromAnnotation($graphClass, $classAnnotation, $currentValue);
283
284 25
        $providerFields = self::getGraphQLFieldsFromProviders($graphClass, $isMutation ? GQL\Mutation::class : GQL\Query::class, $gqlName, $isDefault);
285 25
        $gqlConfiguration['config']['fields'] = array_merge($gqlConfiguration['config']['fields'], $providerFields);
286
287 25
        if ($classAnnotation instanceof GQL\Relay\Edge) {
288 24
            if (!$graphClass->implementsInterface(EdgeInterface::class)) {
289
                throw new InvalidArgumentException(sprintf('The annotation @Edge on class "%s" can only be used on class implementing the EdgeInterface.', $graphClass->getName()));
290
            }
291 24
            if (!isset($gqlConfiguration['config']['builders'])) {
292 24
                $gqlConfiguration['config']['builders'] = [];
293
            }
294 24
            array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classAnnotation->node]]);
295
        }
296
297 25
        return $gqlConfiguration;
298
    }
299
300 25
    private static function graphQLTypeConfigFromAnnotation(GraphClass $graphClass, GQL\Type $typeAnnotation, string $currentValue): array
301
    {
302 25
        $typeConfiguration = [];
303 25
        $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended(), GQL\Field::class, $currentValue);
304 25
        $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getMethods(), GQL\Field::class, $currentValue);
305
306 25
        $typeConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods);
307 25
        $typeConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $typeConfiguration;
308
309 25
        if (isset($typeAnnotation->interfaces)) {
310 24
            $typeConfiguration['interfaces'] = $typeAnnotation->interfaces;
311
        } else {
312 25
            $interfaces = array_keys(self::searchClassesMapBy(function ($gqlType, $configuration) use ($graphClass) {
313 24
                ['class' => $interfaceClassName] = $configuration;
314
315 24
                $interfaceMetadata = self::getGraphClass($interfaceClassName);
316 24
                if ($interfaceMetadata->isInterface() && $graphClass->implementsInterface($interfaceMetadata->getName())) {
317 24
                    return true;
318
                }
319
320 24
                return $graphClass->isSubclassOf($interfaceClassName);
321 25
            }, self::GQL_INTERFACE));
322
323 25
            sort($interfaces);
324 25
            $typeConfiguration['interfaces'] = $interfaces;
325
        }
326
327 25
        if (isset($typeAnnotation->resolveField)) {
328 24
            $typeConfiguration['resolveField'] = self::formatExpression($typeAnnotation->resolveField);
329
        }
330
331 25
        if (isset($typeAnnotation->builders) && !empty($typeAnnotation->builders)) {
332 24
            $typeConfiguration['builders'] = array_map(function ($fieldsBuilderAnnotation) {
333 24
                return ['builder' => $fieldsBuilderAnnotation->builder, 'builderConfig' => $fieldsBuilderAnnotation->builderConfig];
334 24
            }, $typeAnnotation->builders);
335
        }
336
337 25
        if (isset($typeAnnotation->isTypeOf)) {
338 24
            $typeConfiguration['isTypeOf'] = $typeAnnotation->isTypeOf;
339
        }
340
341 25
        $publicAnnotation = self::getFirstAnnotationMatching($graphClass->getAnnotations(), GQL\IsPublic::class);
342 25
        if (null !== $publicAnnotation) {
343 24
            $typeConfiguration['fieldsDefaultPublic'] = self::formatExpression($publicAnnotation->value);
344
        }
345
346 25
        $accessAnnotation = self::getFirstAnnotationMatching($graphClass->getAnnotations(), GQL\Access::class);
347 25
348 24
        if (null !== $accessAnnotation) {
349
            if (isset($accessAnnotation->value)) {
350
                $typeConfiguration['fieldsDefaultAccess'] = self::formatExpression($accessAnnotation->value);
351 25
            }
352
            if (isset($accessAnnotation->nullOnDenied)) {
353
                $typeConfiguration['fieldsDefaultAccessConfig'] = ['nullOnDenied' => $accessAnnotation->nullOnDenied];
354
            }
355
        }
356
357 24
        return ['type' => $typeAnnotation->isRelay ? 'relay-mutation-payload' : 'object', 'config' => $typeConfiguration];
358
    }
359 24
360
    /**
361 24
     * Create a GraphQL Interface type configuration from annotations on properties.
362 24
     */
363
    private static function typeInterfaceAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\TypeInterface $interfaceAnnotation): array
364 24
    {
365 24
        $interfaceConfiguration = [];
366
367 24
        $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended());
368
        $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getMethods());
369 24
370
        $interfaceConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods);
371
        $interfaceConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $interfaceConfiguration;
372
373
        $interfaceConfiguration['resolveType'] = self::formatExpression($interfaceAnnotation->resolveType);
374
375 24
        return ['type' => 'interface', 'config' => $interfaceConfiguration];
376
    }
377 24
378 24
    /**
379 24
     * Create a GraphQL Input type configuration from annotations on properties.
380
     */
381 24
    private static function inputAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Input $inputAnnotation): array
382
    {
383
        $inputConfiguration = array_merge([
384
            'fields' => self::getGraphQLInputFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended()),
385
        ], self::getDescriptionConfiguration($graphClass->getAnnotations()));
386
387 24
        return ['type' => $inputAnnotation->isRelay ? 'relay-mutation-input' : 'input-object', 'config' => $inputConfiguration];
388
    }
389 24
390
    /**
391 24
     * Get a GraphQL scalar configuration from given scalar annotation.
392 24
     */
393
    private static function scalarAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Scalar $scalarAnnotation): array
394
    {
395 24
        $scalarConfiguration = [];
396 24
397 24
        if (isset($scalarAnnotation->scalarType)) {
398
            $scalarConfiguration['scalarType'] = self::formatExpression($scalarAnnotation->scalarType);
399
        } else {
400
            $scalarConfiguration = [
401 24
                'serialize' => [$graphClass->getName(), 'serialize'],
402
                'parseValue' => [$graphClass->getName(), 'parseValue'],
403 24
                'parseLiteral' => [$graphClass->getName(), 'parseLiteral'],
404
            ];
405
        }
406
407
        $scalarConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $scalarConfiguration;
408
409 24
        return ['type' => 'custom-scalar', 'config' => $scalarConfiguration];
410
    }
411 24
412
    /**
413 24
     * Get a GraphQL Enum configuration from given enum annotation.
414
     */
415 24
    private static function enumAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Enum $enumAnnotation): array
416 24
    {
417 24
        $enumValues = $enumAnnotation->values ? $enumAnnotation->values : [];
418 24
419
        $values = [];
420 24
421 24
        foreach ($graphClass->getConstants() as $name => $value) {
422
            $valueAnnotation = current(array_filter($enumValues, fn ($enumValueAnnotation) => $enumValueAnnotation->name == $name));
423
            $valueConfig = [];
424 24
            $valueConfig['value'] = $value;
425 24
426
            if ($valueAnnotation && isset($valueAnnotation->description)) {
427
                $valueConfig['description'] = $valueAnnotation->description;
428 24
            }
429
430
            if ($valueAnnotation && isset($valueAnnotation->deprecationReason)) {
431 24
                $valueConfig['deprecationReason'] = $valueAnnotation->deprecationReason;
432 24
            }
433
434 24
            $values[$name] = $valueConfig;
435
        }
436
437
        $enumConfiguration = ['values' => $values];
438
        $enumConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $enumConfiguration;
439
440 24
        return ['type' => 'enum', 'config' => $enumConfiguration];
441
    }
442 24
443 24
    /**
444 24
     * Get a GraphQL Union configuration from given union annotation.
445
     */
446 24
    private static function unionAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Union $unionAnnotation): array
447 24
    {
448 24
        $unionConfiguration = [];
449
        if (isset($unionAnnotation->types)) {
450 24
            $unionConfiguration['types'] = $unionAnnotation->types;
451 24
        } else {
452
            $types = array_keys(self::searchClassesMapBy(function ($gqlType, $configuration) use ($graphClass) {
453
                $typeClassName = $configuration['class'];
454 24
                $typeMetadata = self::getGraphClass($typeClassName);
455 24
456 24
                if ($graphClass->isInterface() && $typeMetadata->implementsInterface($graphClass->getName())) {
457 24
                    return true;
458
                }
459
460 24
                return $typeMetadata->isSubclassOf($graphClass->getName());
461
            }, self::GQL_TYPE));
462 24
            sort($types);
463 24
            $unionConfiguration['types'] = $types;
464
        }
465 24
466 24
        $unionConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $unionConfiguration;
467 24
468 24
        if (isset($unionAnnotation->resolveType)) {
469
            $unionConfiguration['resolveType'] = self::formatExpression($unionAnnotation->resolveType);
470 24
        } else {
471
            if ($graphClass->hasMethod('resolveType')) {
472
                $method = $graphClass->getMethod('resolveType');
473 1
                if ($method->isStatic() && $method->isPublic()) {
474
                    $unionConfiguration['resolveType'] = self::formatExpression(sprintf("@=call('%s::%s', [service('overblog_graphql.type_resolver'), value], true)", self::formatNamespaceForExpression($graphClass->getName()), 'resolveType'));
475
                } else {
476
                    throw new InvalidArgumentException('The "resolveType()" method on class must be static and public. Or you must define a "resolveType" attribute on the @Union annotation.');
477 24
                }
478
            } else {
479
                throw new InvalidArgumentException('The annotation @Union has no "resolveType" attribute and the related class has no "resolveType()" public static method. You need to define of them.');
480
            }
481
        }
482
483
        return ['type' => 'union', 'config' => $unionConfiguration];
484
    }
485
486 24
    /**
487
     * @phpstan-param ReflectionMethod|ReflectionProperty $reflector
488 24
     * @phpstan-param class-string<GQL\Field> $fieldAnnotationName
489
     *
490 24
     * @throws AnnotationException
491 24
     */
492 24
    private static function getTypeFieldConfigurationFromReflector(GraphClass $graphClass, Reflector $reflector, string $fieldAnnotationName, string $currentValue = 'value'): array
493
    {
494 24
        $annotations = $graphClass->getAnnotations($reflector);
495 24
496 1
        $fieldAnnotation = self::getFirstAnnotationMatching($annotations, $fieldAnnotationName);
497
        $accessAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Access::class);
498
        $publicAnnotation = self::getFirstAnnotationMatching($annotations, GQL\IsPublic::class);
499 24
500
        if (null === $fieldAnnotation) {
501
            if (null !== $accessAnnotation || null !== $publicAnnotation) {
502 24
                throw new InvalidArgumentException(sprintf('The annotations "@Access" and/or "@Visible" defined on "%s" are only usable in addition of annotation "@Field"', $reflector->getName()));
503 1
            }
504
505
            return [];
506 24
        }
507 24
508
        if ($reflector instanceof ReflectionMethod && !$reflector->isPublic()) {
509 24
            throw new InvalidArgumentException(sprintf('The Annotation "@Field" can only be applied to public method. The method "%s" is not public.', $reflector->getName()));
510 24
        }
511
512
        $fieldName = $reflector->getName();
513 24
        $fieldConfiguration = [];
514
515 24
        if (isset($fieldAnnotation->type)) {
516
            $fieldConfiguration['type'] = $fieldAnnotation->type;
517 24
        }
518 24
519
        $fieldConfiguration = self::getDescriptionConfiguration($annotations, true) + $fieldConfiguration;
520 24
521 24
        $args = [];
522
523
        foreach ($fieldAnnotation->args as $arg) {
524 24
            $args[$arg->name] = ['type' => $arg->type];
525 24
526
            if (isset($arg->description)) {
527
                $args[$arg->name]['description'] = $arg->description;
528
            }
529 24
530 24
            if (isset($arg->default)) {
531
                $args[$arg->name]['defaultValue'] = $arg->default;
532
            }
533 24
        }
534 24
535
        if (empty($fieldAnnotation->args) && $reflector instanceof ReflectionMethod) {
536
            $args = self::guessArgs($reflector);
537 24
        }
538
539 24
        if (!empty($args)) {
540 24
            $fieldConfiguration['args'] = $args;
541
        }
542 24
543 24
        $fieldName = $fieldAnnotation->name ?? $fieldName;
544
545 24
        if (isset($fieldAnnotation->resolve)) {
546
            $fieldConfiguration['resolve'] = self::formatExpression($fieldAnnotation->resolve);
547
        } else {
548
            if ($reflector instanceof ReflectionMethod) {
549
                $fieldConfiguration['resolve'] = self::formatExpression(sprintf('call(%s.%s, %s)', $currentValue, $reflector->getName(), self::formatArgsForExpression($args)));
550
            } else {
551 24
                if ($fieldName !== $reflector->getName() || 'value' !== $currentValue) {
552 24
                    $fieldConfiguration['resolve'] = self::formatExpression(sprintf('%s.%s', $currentValue, $reflector->getName()));
553
                }
554 24
            }
555 24
        }
556 24
557
        if ($fieldAnnotation->argsBuilder) {
558
            if (is_string($fieldAnnotation->argsBuilder)) {
559
                $fieldConfiguration['argsBuilder'] = $fieldAnnotation->argsBuilder;
560
            } elseif (is_array($fieldAnnotation->argsBuilder)) {
561
                list($builder, $builderConfig) = $fieldAnnotation->argsBuilder;
562 24
                $fieldConfiguration['argsBuilder'] = ['builder' => $builder, 'config' => $builderConfig];
563 24
            } else {
564
                throw new InvalidArgumentException(sprintf('The attribute "argsBuilder" on GraphQL annotation "@%s" defined on "%s" must be a string or an array where first index is the builder name and the second is the config.', $fieldAnnotationName, $reflector->getName()));
565 24
            }
566 24
        }
567 24
568 24
        if ($fieldAnnotation->fieldBuilder) {
569
            if (is_string($fieldAnnotation->fieldBuilder)) {
570 24
                $fieldConfiguration['builder'] = $fieldAnnotation->fieldBuilder;
571
            } elseif (is_array($fieldAnnotation->fieldBuilder)) {
572
                list($builder, $builderConfig) = $fieldAnnotation->fieldBuilder;
573 24
                $fieldConfiguration['builder'] = $builder;
574 24
                $fieldConfiguration['builderConfig'] = $builderConfig ?: [];
575
            } else {
576 24
                throw new InvalidArgumentException(sprintf('The attribute "fieldBuilder" on GraphQL annotation "@%s" defined on "%s" must be a string or an array where first index is the builder name and the second is the config.', $fieldAnnotationName, $reflector->getName()));
577
            }
578
        } else {
579 24
            if (!isset($fieldAnnotation->type)) {
580
                if ($reflector instanceof ReflectionMethod) {
581 24
                    /** @var ReflectionMethod $reflector */
582
                    if ($reflector->hasReturnType()) {
583
                        try {
584 24
                            // @phpstan-ignore-next-line
585
                            $fieldConfiguration['type'] = self::resolveGraphQLTypeFromReflectionType($reflector->getReturnType(), self::VALID_OUTPUT_TYPES);
586
                        } catch (Exception $e) {
587
                            throw new InvalidArgumentException(sprintf('The attribute "type" on GraphQL annotation "@%s" is missing on method "%s" and cannot be auto-guessed from type hint "%s"', $fieldAnnotationName, $reflector->getName(), (string) $reflector->getReturnType()));
588 24
                        }
589 2
                    } else {
590 2
                        throw new InvalidArgumentException(sprintf('The attribute "type" on GraphQL annotation "@%s" is missing on method "%s" and cannot be auto-guessed as there is not return type hint.', $fieldAnnotationName, $reflector->getName()));
591
                    }
592
                } else {
593
                    try {
594
                        $fieldConfiguration['type'] = self::guessType($graphClass, $annotations);
595
                    } catch (Exception $e) {
596 24
                        throw new InvalidArgumentException(sprintf('The attribute "type" on "@%s" defined on "%s" is required and cannot be auto-guessed : %s.', $fieldAnnotationName, $reflector->getName(), $e->getMessage()));
597 24
                    }
598
                }
599
            }
600 24
        }
601 24
602
        if (null !== $accessAnnotation) {
603
            if (isset($accessAnnotation->value)) {
604 24
                $fieldConfiguration['access'] = self::formatExpression($accessAnnotation->value);
605 24
            }
606
            if (isset($accessAnnotation->nullOnDenied)) {
607
                $fieldConfiguration['accessConfig'] = ['nullOnDenied' => $accessAnnotation->nullOnDenied];
608 24
            }
609
        }
610
611
        if ($publicAnnotation) {
612
            $fieldConfiguration['public'] = self::formatExpression($publicAnnotation->value);
613
        }
614
615
        if ($fieldAnnotation->complexity) {
616
            $fieldConfiguration['complexity'] = self::formatExpression($fieldAnnotation->complexity);
617
        }
618 24
619
        return [$fieldName => $fieldConfiguration];
620 24
    }
621
622 24
    /**
623 24
     * Create GraphQL input fields configuration based on annotations.
624
     *
625
     * @param ReflectionProperty[] $reflectors
626 24
     *
627
     * @throws AnnotationException
628
     */
629 24
    private static function getGraphQLInputFieldsFromAnnotations(GraphClass $graphClass, array $reflectors): array
630
    {
631
        $fields = [];
632
633 24
        foreach ($reflectors as $reflector) {
634 24
            $annotations = $graphClass->getAnnotations($reflector);
635 24
636 24
            /** @var GQL\Field $fieldAnnotation */
637
            $fieldAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Field::class);
638 24
639
            // Ignore field with resolver when the type is an Input
640 24
            if (isset($fieldAnnotation->resolve)) {
641
                return [];
642
            }
643
644 24
            $fieldName = $reflector->getName();
645
            $fieldType = $fieldAnnotation->type;
646
            $fieldConfiguration = [];
647 24
            if ($fieldType) {
648 24
                // Resolve a PHP class from a GraphQL type
649
                $resolvedType = self::$classesMap[$fieldType] ?? null;
650
                // We found a type but it is not allowed
651 24
                if (null !== $resolvedType && !in_array($resolvedType['type'], self::VALID_INPUT_TYPES)) {
652
                    throw new InvalidArgumentException(sprintf('The type "%s" on "%s" is a "%s" not valid on an Input @Field. Only Input, Scalar and Enum are allowed.', $fieldType, $reflector->getName(), $resolvedType['type']));
653
                }
654
655
                $fieldConfiguration['type'] = $fieldType;
656
            }
657
658
            $fieldConfiguration = array_merge(self::getDescriptionConfiguration($annotations, true), $fieldConfiguration);
659
            $fields[$fieldName] = $fieldConfiguration;
660
        }
661
662
        return $fields;
663 25
    }
664
665 25
    /**
666
     * Create GraphQL type fields configuration based on annotations.
667 25
     *
668 24
     * @phpstan-param class-string<GQL\Field> $fieldAnnotationName
669
     *
670
     * @param ReflectionProperty[]|ReflectionMethod[] $reflectors
671 25
     *
672
     * @throws AnnotationException
673
     */
674
    private static function getGraphQLTypeFieldsFromAnnotations(GraphClass $graphClass, array $reflectors, string $fieldAnnotationName = GQL\Field::class, string $currentValue = 'value'): array
675
    {
676
        $fields = [];
677
678
        foreach ($reflectors as $reflector) {
679
            $fields = array_merge($fields, self::getTypeFieldConfigurationFromReflector($graphClass, $reflector, $fieldAnnotationName, $currentValue));
680 25
        }
681
682 25
        return $fields;
683 25
    }
684 24
685 24
    /**
686
     * @phpstan-param class-string<GQL\Query|GQL\Mutation> $expectedAnnotation
687 24
     *
688 24
     * Return fields config from Provider methods.
689
     * Loop through configured provider and extract fields targeting the targetType.
690 24
     */
691
    private static function getGraphQLFieldsFromProviders(GraphClass $graphClass, string $expectedAnnotation, string $targetType, bool $isDefaultTarget = false): array
692 24
    {
693 24
        $fields = [];
694
        foreach (self::$providers as ['metadata' => $providerMetadata, 'annotation' => $providerAnnotation]) {
695 24
            $defaultAccessAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\Access::class);
696 24
            $defaultIsPublicAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\IsPublic::class);
697
698
            $defaultAccess = isset($defaultAccessAnnotation->value) ? self::formatExpression($defaultAccessAnnotation->value) : false;
699
            $defaultAccessConfig = isset($defaultAccessAnnotation->nullOnDenied) ? ['nullOnDenied' => $defaultAccessAnnotation->nullOnDenied] : false;
700 24
            $defaultIsPublic = $defaultIsPublicAnnotation ? self::formatExpression($defaultIsPublicAnnotation->value) : false;
701
702 24
            $methods = [];
703 24
            // First found the methods matching the targeted type
704 24
            foreach ($providerMetadata->getMethods() as $method) {
705 24
                $annotations = $providerMetadata->getAnnotations($method);
706 24
707
                $annotation = self::getFirstAnnotationMatching($annotations, [GQL\Mutation::class, GQL\Query::class]);
708
                if (null === $annotation) {
709 24
                    continue;
710
                }
711
712
                $annotationTargets = $annotation->targetType ?? null;
713 24
714 24
                if (null === $annotationTargets) {
715
                    if ($isDefaultTarget) {
716
                        $annotationTargets = [$targetType];
717 24
                        if (!$annotation instanceof $expectedAnnotation) {
718 2
                            continue;
719 1
                        }
720
                    } else {
721 1
                        continue;
722
                    }
723
                }
724 2
725
                if (!in_array($targetType, $annotationTargets)) {
726 24
                    continue;
727
                }
728
729 24
                if (!$annotation instanceof $expectedAnnotation) {
730 24
                    if (GQL\Mutation::class == $expectedAnnotation) {
731 24
                        $message = sprintf('The provider "%s" try to add a query field on type "%s" (through @Query on method "%s") but "%s" is a mutation.', $providerMetadata->getName(), $targetType, $method->getName(), $targetType);
732 24
                    } else {
733 24
                        $message = sprintf('The provider "%s" try to add a mutation on type "%s" (through @Mutation on method "%s") but "%s" is not a mutation.', $providerMetadata->getName(), $targetType, $method->getName(), $targetType);
734
                    }
735
736 24
                    throw new InvalidArgumentException($message);
737 24
                }
738
                $methods[$method->getName()] = $method;
739
            }
740 24
741 24
            $currentValue = sprintf("service('%s')", self::formatNamespaceForExpression($providerMetadata->getName()));
742
            $providerFields = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $methods, $expectedAnnotation, $currentValue);
743
            foreach ($providerFields as $fieldName => $fieldConfig) {
744 24
                if ($providerAnnotation->prefix) {
745
                    $fieldName = sprintf('%s%s', $providerAnnotation->prefix, $fieldName);
746
                }
747
748 25
                if ($defaultAccess && !isset($fieldConfig['access'])) {
749
                    $fieldConfig['access'] = $defaultAccess;
750
                }
751
752
                if ($defaultAccessConfig && !isset($fieldConfig['accessConfig'])) {
753
                    $fieldConfig['accessConfig'] = $defaultAccessConfig;
754 25
                }
755
756 25
                if ($defaultIsPublic && !isset($fieldConfig['public'])) {
757 25
                    $fieldConfig['public'] = $defaultIsPublic;
758 25
                }
759 24
760
                $fields[$fieldName] = $fieldConfig;
761
            }
762 25
        }
763 24
764 24
        return $fields;
765 24
    }
766
767
    /**
768
     * Get the config for description & deprecation reason.
769 25
     */
770
    private static function getDescriptionConfiguration(array $annotations, bool $withDeprecation = false): array
771
    {
772
        $config = [];
773
        $descriptionAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Description::class);
774
        if (null !== $descriptionAnnotation) {
775 24
            $config['description'] = $descriptionAnnotation->value;
776
        }
777 24
778 24
        if ($withDeprecation) {
779 24
            $deprecatedAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Deprecated::class);
780
            if (null !== $deprecatedAnnotation) {
781
                $config['deprecationReason'] = $deprecatedAnnotation->value;
782 24
            }
783
        }
784
785
        return $config;
786
    }
787
788 24
    /**
789
     * Format an array of args to a list of arguments in an expression.
790 24
     */
791
    private static function formatArgsForExpression(array $args): string
792
    {
793
        $mapping = [];
794
        foreach ($args as $name => $config) {
795
            $mapping[] = sprintf('%s: "%s"', $name, $config['type']);
796
        }
797
798
        return sprintf('arguments({%s}, args)', implode(', ', $mapping));
799
    }
800
801
    /**
802
     * Format a namespace to be used in an expression (double escape).
803
     */
804 25
    private static function formatNamespaceForExpression(string $namespace): string
805
    {
806 25
        return str_replace('\\', '\\\\', $namespace);
807 25
    }
808
809
    /**
810 25
     * Get the first annotation matching given class.
811 25
     *
812 25
     * @phpstan-template T of object
813 24
     * @phpstan-param class-string<T>|class-string<T>[] $annotationClass
814
     * @phpstan-return T|null
815
     *
816
     * @param string|array $annotationClass
817
     *
818 25
     * @return object|null
819
     */
820
    private static function getFirstAnnotationMatching(array $annotations, $annotationClass)
821
    {
822
        if (is_string($annotationClass)) {
823
            $annotationClass = [$annotationClass];
824 24
        }
825
826 24
        foreach ($annotations as $annotation) {
827
            foreach ($annotationClass as $class) {
828
                if ($annotation instanceof $class) {
829
                    return $annotation;
830
                }
831
            }
832 24
        }
833
834 24
        return null;
835
    }
836
837
    /**
838
     * Format an expression (ie. add "@=" if not set).
839
     */
840
    private static function formatExpression(string $expression): string
841
    {
842 24
        return '@=' === substr($expression, 0, 2) ? $expression : sprintf('@=%s', $expression);
843
    }
844 24
845 24
    /**
846 24
     * Suffix a name if it is not already.
847 24
     */
848 24
    private static function suffixName(string $name, string $suffix): string
849 24
    {
850
        return substr($name, -strlen($suffix)) === $suffix ? $name : sprintf('%s%s', $name, $suffix);
851 1
    }
852
853
    /**
854
     * Try to guess a field type base on his annotations.
855
     *
856 24
     * @throws RuntimeException
857
     */
858
    private static function guessType(GraphClass $graphClass, array $annotations): string
859
    {
860
        $columnAnnotation = self::getFirstAnnotationMatching($annotations, Column::class);
861
        if (null !== $columnAnnotation) {
862 24
            $type = self::resolveTypeFromDoctrineType($columnAnnotation->type);
863 24
            $nullable = $columnAnnotation->nullable;
864 24
            if ($type) {
865 24
                return $nullable ? $type : sprintf('%s!', $type);
866
            } else {
867 24
                throw new RuntimeException(sprintf('Unable to auto-guess GraphQL type from Doctrine type "%s"', $columnAnnotation->type));
868 24
            }
869 24
        }
870 24
871
        $associationAnnotations = [
872 24
            OneToMany::class => true,
873 24
            OneToOne::class => false,
874 24
            ManyToMany::class => true,
875 24
            ManyToOne::class => false,
876
        ];
877
878 24
        $associationAnnotation = self::getFirstAnnotationMatching($annotations, array_keys($associationAnnotations));
879
        if (null !== $associationAnnotation) {
880
            $target = self::fullyQualifiedClassName($associationAnnotation->targetEntity, $graphClass->getNamespaceName());
881 1
            $type = self::resolveTypeFromClass($target, ['type']);
882
883
            if ($type) {
884
                $isMultiple = $associationAnnotations[get_class($associationAnnotation)];
885
                if ($isMultiple) {
886
                    return sprintf('[%s]!', $type);
887
                } else {
888
                    $isNullable = false;
889
                    $joinColumn = self::getFirstAnnotationMatching($annotations, JoinColumn::class);
890
                    if (null !== $joinColumn) {
891
                        $isNullable = $joinColumn->nullable;
892
                    }
893 24
894
                    return sprintf('%s%s', $type, $isNullable ? '' : '!');
895 24
                }
896 24
            } else {
897
                throw new RuntimeException(sprintf('Unable to auto-guess GraphQL type from Doctrine target class "%s" (check if the target class is a GraphQL type itself (with a @GQL\Type annotation).', $target));
898
            }
899 1
        }
900
901
        throw new InvalidArgumentException('No Doctrine ORM annotation found.');
902
    }
903
904
    /**
905 24
     * Resolve a FQN from classname and namespace.
906
     *
907 24
     * @internal
908 24
     */
909
    public static function fullyQualifiedClassName(string $className, string $namespace): string
910
    {
911
        if (false === strpos($className, '\\') && $namespace) {
912 24
            return $namespace.'\\'.$className;
913 24
        }
914 24
915 24
        return $className;
916 24
    }
917 1
918 24
    /**
919 1
     * Resolve a GraphQLType from a doctrine type.
920 1
     */
921
    private static function resolveTypeFromDoctrineType(string $doctrineType): ?string
922 1
    {
923 1
        if (isset(self::$doctrineMapping[$doctrineType])) {
924
            return self::$doctrineMapping[$doctrineType];
925
        }
926 1
927
        switch ($doctrineType) {
928
            case 'integer':
929
            case 'smallint':
930
            case 'bigint':
931
                return 'Int';
932
            case 'string':
933 24
            case 'text':
934
                return 'String';
935 24
            case 'bool':
936 24
            case 'boolean':
937 24
                return 'Boolean';
938 1
            case 'float':
939
            case 'decimal':
940
                return 'Float';
941
            default:
942
                return null;
943 24
        }
944
    }
945
946
    /**
947
     * Transform a method arguments from reflection to a list of GraphQL argument.
948 24
     */
949 24
    private static function guessArgs(ReflectionMethod $method): array
950 24
    {
951
        $arguments = [];
952
        foreach ($method->getParameters() as $index => $parameter) {
953 24
            if (!$parameter->hasType()) {
954
                throw new InvalidArgumentException(sprintf('Argument n°%s "$%s" on method "%s" cannot be auto-guessed as there is not type hint.', $index + 1, $parameter->getName(), $method->getName()));
955 24
            }
956
957
            try {
958 24
                // @phpstan-ignore-next-line
959
                $gqlType = self::resolveGraphQLTypeFromReflectionType($parameter->getType(), self::VALID_INPUT_TYPES, $parameter->isDefaultValueAvailable());
960
            } catch (Exception $e) {
961 24
                throw new InvalidArgumentException(sprintf('Argument n°%s "$%s" on method "%s" cannot be auto-guessed : %s".', $index + 1, $parameter->getName(), $method->getName(), $e->getMessage()));
962
            }
963 24
964 24
            $argumentConfig = [];
965 24
            if ($parameter->isDefaultValueAvailable()) {
966 24
                $argumentConfig['defaultValue'] = $parameter->getDefaultValue();
967 24
            }
968
969
            $argumentConfig['type'] = $gqlType;
970 24
971 24
            $arguments[$parameter->getName()] = $argumentConfig;
972
        }
973
974
        return $arguments;
975
    }
976 24
977
    private static function resolveGraphQLTypeFromReflectionType(ReflectionNamedType $type, array $filterGraphQLTypes = [], bool $isOptional = false): string
978
    {
979
        $sType = $type->getName();
980
        if ($type->isBuiltin()) {
981
            $gqlType = self::resolveTypeFromPhpType($sType);
982 24
            if (null === $gqlType) {
983
                throw new RuntimeException(sprintf('No corresponding GraphQL type found for builtin type "%s"', $sType));
984 24
            }
985 24
        } else {
986 24
            $gqlType = self::resolveTypeFromClass($sType, $filterGraphQLTypes);
987 24
            if (null === $gqlType) {
988
                throw new RuntimeException(sprintf('No corresponding GraphQL %s found for class "%s"', $filterGraphQLTypes ? implode(',', $filterGraphQLTypes) : 'object', $sType));
989
            }
990
        }
991
992 1
        return sprintf('%s%s', $gqlType, ($type->allowsNull() || $isOptional) ? '' : '!');
993
    }
994
995
    /**
996
     * Resolve a GraphQL Type from a class name.
997
     */
998
    private static function resolveTypeFromClass(string $className, array $wantedTypes = []): ?string
999
    {
1000 25
        foreach (self::$classesMap as $gqlType => $config) {
1001
            if ($config['class'] === $className) {
1002 25
                if (in_array($config['type'], $wantedTypes)) {
1003 25
                    return $gqlType;
1004 25
                }
1005 25
            }
1006
        }
1007
1008 24
        return null;
1009 24
    }
1010
1011
    /**
1012
     * Search the classes map for class by predicate.
1013 25
     *
1014
     * @return array
1015
     */
1016
    private static function searchClassesMapBy(callable $predicate, string $type)
1017
    {
1018
        $classNames = [];
1019 24
        foreach (self::$classesMap as $gqlType => $config) {
1020
            if ($config['type'] !== $type) {
1021
                continue;
1022 24
            }
1023 24
1024 24
            if ($predicate($gqlType, $config)) {
1025 24
                $classNames[$gqlType] = $config;
1026 24
            }
1027 24
        }
1028 24
1029 24
        return $classNames;
1030 24
    }
1031 24
1032 24
    /**
1033
     * Convert a PHP Builtin type to a GraphQL type.
1034
     */
1035
    private static function resolveTypeFromPhpType(string $phpType): ?string
1036
    {
1037
        switch ($phpType) {
1038 1
            case 'boolean':
1039
            case 'bool':
1040
                return 'Boolean';
1041
            case 'integer':
1042
            case 'int':
1043
                return 'Int';
1044
            case 'float':
1045
            case 'double':
1046
                return 'Float';
1047
            case 'string':
1048
                return 'String';
1049
            default:
1050
                return null;
1051
        }
1052
    }
1053
}
1054