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 (#710)
by Vincent
25:24 queued 23:03
created

AnnotationParser::guessArgs()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0729

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 26
ccs 12
cts 14
cp 0.8571
rs 9.4888
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 5.0729
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Overblog\GraphQLBundle\Config\Parser;
6
7
use Doctrine\ORM\Mapping\Column;
8
use Doctrine\ORM\Mapping\JoinColumn;
9
use Doctrine\ORM\Mapping\ManyToMany;
10
use Doctrine\ORM\Mapping\ManyToOne;
11
use Doctrine\ORM\Mapping\OneToMany;
12
use Doctrine\ORM\Mapping\OneToOne;
13
use Exception;
14
use Overblog\GraphQLBundle\Annotation as GQL;
15
use Overblog\GraphQLBundle\Config\Parser\Annotation\GraphClass;
16
use Overblog\GraphQLBundle\Relay\Connection\ConnectionInterface;
17
use Overblog\GraphQLBundle\Relay\Connection\EdgeInterface;
18
use ReflectionException;
19
use ReflectionMethod;
20
use ReflectionNamedType;
21
use ReflectionProperty;
22
use Reflector;
23
use RuntimeException;
24
use SplFileInfo;
25
use Symfony\Component\Config\Resource\FileResource;
26
use Symfony\Component\DependencyInjection\ContainerBuilder;
27
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
28
use function array_filter;
29
use function array_keys;
30
use function array_map;
31
use function array_unshift;
32
use function current;
33
use function file_get_contents;
34
use function get_class;
35
use function implode;
36
use function in_array;
37
use function is_array;
38
use function is_string;
39
use function preg_match;
40
use function sprintf;
41
use function str_replace;
42
use function strlen;
43
use function strpos;
44
use function substr;
45
use function trim;
46
47
class AnnotationParser implements PreParserInterface
48
{
49
    private static array $classesMap = [];
50
    private static array $providers = [];
51
    private static array $doctrineMapping = [];
52
    private static array $graphClassCache = [];
53
54
    private const GQL_SCALAR = 'scalar';
55
    private const GQL_ENUM = 'enum';
56
    private const GQL_TYPE = 'type';
57
    private const GQL_INPUT = 'input';
58
    private const GQL_UNION = 'union';
59
    private const GQL_INTERFACE = 'interface';
60
61
    /**
62
     * @see https://facebook.github.io/graphql/draft/#sec-Input-and-Output-Types
63
     */
64
    private const VALID_INPUT_TYPES = [self::GQL_SCALAR, self::GQL_ENUM, self::GQL_INPUT];
65
    private const VALID_OUTPUT_TYPES = [self::GQL_SCALAR, self::GQL_TYPE, self::GQL_INTERFACE, self::GQL_UNION, self::GQL_ENUM];
66
67
    /**
68
     * {@inheritdoc}
69
     *
70
     * @throws InvalidArgumentException
71
     */
72 25
    public static function preParse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): void
73
    {
74 25
        $container->setParameter('overblog_graphql_types.classes_map', self::processFile($file, $container, $configs, true));
75 25
    }
76
77
    /**
78
     * @throws InvalidArgumentException
79
     */
80 25
    public static function parse(SplFileInfo $file, ContainerBuilder $container, array $configs = []): array
81
    {
82 25
        return self::processFile($file, $container, $configs, false);
83
    }
84
85
    /**
86
     * @internal
87
     */
88 63
    public static function reset(): void
89
    {
90 63
        self::$classesMap = [];
91 63
        self::$providers = [];
92 63
        self::$graphClassCache = [];
93 63
    }
94
95
    /**
96
     * Process a file.
97
     *
98
     * @throws InvalidArgumentException
99
     * @throws ReflectionException
100
     */
101 25
    private static function processFile(SplFileInfo $file, ContainerBuilder $container, array $configs, bool $preProcess): array
102
    {
103 25
        self::$doctrineMapping = $configs['doctrine']['types_mapping'];
104 25
        $container->addResource(new FileResource($file->getRealPath()));
105
106
        try {
107 25
            $className = $file->getBasename('.php');
108 25
            if (preg_match('#namespace (.+);#', file_get_contents($file->getRealPath()), $matches)) {
109 25
                $className = trim($matches[1]).'\\'.$className;
110
            }
111
112 25
            $gqlTypes = [];
113 25
            $graphClass = self::getGraphClass($className);
114
115 25
            foreach ($graphClass->getAnnotations() as $classAnnotation) {
116 25
                $gqlTypes = self::classAnnotationsToGQLConfiguration(
117 25
                    $graphClass,
118
                    $classAnnotation,
119
                    $configs,
120
                    $gqlTypes,
121
                    $preProcess
122
                );
123
            }
124
125 25
            return $preProcess ? self::$classesMap : $gqlTypes;
126 10
        } catch (\InvalidArgumentException $e) {
127 10
            throw new InvalidArgumentException(sprintf('Failed to parse GraphQL annotations from file "%s".', $file), $e->getCode(), $e);
128
        }
129
    }
130
131 25
    private static function classAnnotationsToGQLConfiguration(
132
        GraphClass $graphClass,
133
        object $classAnnotation,
134
        array $configs,
135
        array $gqlTypes,
136
        bool $preProcess
137
    ): array {
138 25
        $gqlConfiguration = $gqlType = $gqlName = null;
139
140
        switch (true) {
141 25
            case $classAnnotation instanceof GQL\Type:
142 25
                $gqlType = self::GQL_TYPE;
143 25
                $gqlName = $classAnnotation->name ?: $graphClass->getShortName();
144 25
                if (!$preProcess) {
145 25
                    $gqlConfiguration = self::typeAnnotationToGQLConfiguration($graphClass, $classAnnotation, $gqlName, $configs);
146
147 25
                    if ($classAnnotation instanceof GQL\Relay\Connection) {
148 24
                        if (!$graphClass->implementsInterface(ConnectionInterface::class)) {
149
                            throw new InvalidArgumentException(sprintf('The annotation @Connection on class "%s" can only be used on class implementing the ConnectionInterface.', $graphClass->getName()));
150
                        }
151
152 24
                        if (!($classAnnotation->edge xor $classAnnotation->node)) {
153
                            throw new InvalidArgumentException(sprintf('The annotation @Connection on class "%s" is invalid. You must define the "edge" OR the "node" attribute.', $graphClass->getName()));
154
                        }
155
156 24
                        $edgeType = $classAnnotation->edge;
157 24
                        if (!$edgeType) {
158 24
                            $edgeType = sprintf('%sEdge', $gqlName);
159 24
                            $gqlTypes[$edgeType] = [
160 24
                                'type' => 'object',
161
                                'config' => [
162
                                    'builders' => [
163 24
                                        ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classAnnotation->node]],
164
                                    ],
165
                                ],
166
                            ];
167
                        }
168 24
                        if (!isset($gqlConfiguration['config']['builders'])) {
169 24
                            $gqlConfiguration['config']['builders'] = [];
170
                        }
171 24
                        array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-connection', 'builderConfig' => ['edgeType' => $edgeType]]);
172
                    }
173
                }
174 25
                break;
175
176 24
            case $classAnnotation instanceof GQL\Input:
177 24
                $gqlType = self::GQL_INPUT;
178 24
                $gqlName = $classAnnotation->name ?: self::suffixName($graphClass->getShortName(), 'Input');
179 24
                if (!$preProcess) {
180 24
                    $gqlConfiguration = self::inputAnnotationToGQLConfiguration($graphClass, $classAnnotation);
181
                }
182 24
                break;
183
184 24
            case $classAnnotation instanceof GQL\Scalar:
185 24
                $gqlType = self::GQL_SCALAR;
186 24
                if (!$preProcess) {
187 24
                    $gqlConfiguration = self::scalarAnnotationToGQLConfiguration($graphClass, $classAnnotation);
188
                }
189 24
                break;
190
191 24
            case $classAnnotation instanceof GQL\Enum:
192 24
                $gqlType = self::GQL_ENUM;
193 24
                if (!$preProcess) {
194 24
                    $gqlConfiguration = self::enumAnnotationToGQLConfiguration($graphClass, $classAnnotation);
195
                }
196 24
                break;
197
198 24
            case $classAnnotation instanceof GQL\Union:
199 24
                $gqlType = self::GQL_UNION;
200 24
                if (!$preProcess) {
201 24
                    $gqlConfiguration = self::unionAnnotationToGQLConfiguration($graphClass, $classAnnotation);
202
                }
203 24
                break;
204
205 24
            case $classAnnotation instanceof GQL\TypeInterface:
206 24
                $gqlType = self::GQL_INTERFACE;
207 24
                if (!$preProcess) {
208 24
                    $gqlConfiguration = self::typeInterfaceAnnotationToGQLConfiguration($graphClass, $classAnnotation);
209
                }
210 24
                break;
211
212 24
            case $classAnnotation instanceof GQL\Provider:
213 24
                if ($preProcess) {
214 24
                    self::$providers[] = ['metadata' => $graphClass, 'annotation' => $classAnnotation];
215
                }
216
217 24
                return [];
218
        }
219
220 25
        if (null !== $gqlType) {
221 25
            if (!$gqlName) {
222 24
                $gqlName = $classAnnotation->name ?: $graphClass->getShortName();
223
            }
224
225 25
            if ($preProcess) {
226 25
                if (isset(self::$classesMap[$gqlName])) {
227 1
                    throw new InvalidArgumentException(sprintf('The GraphQL type "%s" has already been registered in class "%s"', $gqlName, self::$classesMap[$gqlName]['class']));
228
                }
229 25
                self::$classesMap[$gqlName] = ['type' => $gqlType, 'class' => $graphClass->getName()];
230
            } else {
231 25
                $gqlTypes = [$gqlName => $gqlConfiguration] + $gqlTypes;
232
            }
233
        }
234
235 25
        return $gqlTypes;
236
    }
237
238
    /**
239
     * @throws ReflectionException
240
     */
241 25
    private static function getGraphClass(string $className): GraphClass
242
    {
243 25
        self::$graphClassCache[$className] ??= new GraphClass($className);
244
245 25
        return self::$graphClassCache[$className];
246
    }
247
248 25
    private static function typeAnnotationToGQLConfiguration(
249
        GraphClass $graphClass,
250
        GQL\Type $classAnnotation,
251
        string $gqlName,
252
        array $configs
253
    ): array {
254 25
        $isMutation = $isDefault = $isRoot = false;
255 25
        if (isset($configs['definitions']['schema'])) {
256 24
            foreach ($configs['definitions']['schema'] as $schemaName => $schema) {
257 24
                $schemaQuery = $schema['query'] ?? null;
258 24
                $schemaMutation = $schema['mutation'] ?? null;
259
260 24
                if ($schemaQuery && $gqlName === $schemaQuery) {
261 24
                    $isRoot = true;
262 24
                    if ('default' == $schemaName) {
263 24
                        $isDefault = true;
264
                    }
265 24
                } elseif ($schemaMutation && $gqlName === $schemaMutation) {
266 24
                    $isMutation = true;
267 24
                    $isRoot = true;
268 24
                    if ('default' == $schemaName) {
269 24
                        $isDefault = true;
270
                    }
271
                }
272
            }
273
        }
274
275 25
        $currentValue = $isRoot ? sprintf("service('%s')", self::formatNamespaceForExpression($graphClass->getName())) : 'value';
276
277 25
        $gqlConfiguration = self::graphQLTypeConfigFromAnnotation($graphClass, $classAnnotation, $currentValue);
278
279 25
        $providerFields = self::getGraphQLFieldsFromProviders($graphClass, $isMutation ? GQL\Mutation::class : GQL\Query::class, $gqlName, $isDefault);
280 25
        $gqlConfiguration['config']['fields'] = array_merge($gqlConfiguration['config']['fields'], $providerFields);
281
282 25
        if ($classAnnotation instanceof GQL\Relay\Edge) {
283 24
            if (!$graphClass->implementsInterface(EdgeInterface::class)) {
284
                throw new InvalidArgumentException(sprintf('The annotation @Edge on class "%s" can only be used on class implementing the EdgeInterface.', $graphClass->getName()));
285
            }
286 24
            if (!isset($gqlConfiguration['config']['builders'])) {
287 24
                $gqlConfiguration['config']['builders'] = [];
288
            }
289 24
            array_unshift($gqlConfiguration['config']['builders'], ['builder' => 'relay-edge', 'builderConfig' => ['nodeType' => $classAnnotation->node]]);
290
        }
291
292 25
        return $gqlConfiguration;
293
    }
294
295 25
    private static function graphQLTypeConfigFromAnnotation(GraphClass $graphClass, GQL\Type $typeAnnotation, string $currentValue): array
296
    {
297 25
        $typeConfiguration = [];
298 25
        $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended(), GQL\Field::class, $currentValue);
299 25
        $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getMethods(), GQL\Field::class, $currentValue);
300
301 25
        $typeConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods);
302 25
        $typeConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $typeConfiguration;
303
304 25
        if (null !== $typeAnnotation->interfaces) {
305 24
            $typeConfiguration['interfaces'] = $typeAnnotation->interfaces;
306
        } else {
307
            $interfaces = array_keys(self::searchClassesMapBy(function ($gqlType, $configuration) use ($graphClass) {
308 24
                ['class' => $interfaceClassName] = $configuration;
309
310 24
                $interfaceMetadata = self::getGraphClass($interfaceClassName);
311 24
                if ($interfaceMetadata->isInterface() && $graphClass->implementsInterface($interfaceMetadata->getName())) {
312 24
                    return true;
313
                }
314
315 24
                return $graphClass->isSubclassOf($interfaceClassName);
316 25
            }, self::GQL_INTERFACE));
317
318 25
            sort($interfaces);
319 25
            $typeConfiguration['interfaces'] = $interfaces;
320
        }
321
322 25
        if ($typeAnnotation->resolveField) {
323 24
            $typeConfiguration['resolveField'] = self::formatExpression($typeAnnotation->resolveField);
324
        }
325
326 25
        if ($typeAnnotation->builders && !empty($typeAnnotation->builders)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $typeAnnotation->builders of type Overblog\GraphQLBundle\Annotation\FieldsBuilder[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
327
            $typeConfiguration['builders'] = array_map(function ($fieldsBuilderAnnotation) {
328 24
                return ['builder' => $fieldsBuilderAnnotation->builder, 'builderConfig' => $fieldsBuilderAnnotation->builderConfig];
329 24
            }, $typeAnnotation->builders);
330
        }
331
332 25
        if ($typeAnnotation->isTypeOf) {
333 24
            $typeConfiguration['isTypeOf'] = $typeAnnotation->isTypeOf;
334
        }
335
336 25
        $publicAnnotation = self::getFirstAnnotationMatching($graphClass->getAnnotations(), GQL\IsPublic::class);
337 25
        if ($publicAnnotation) {
338 24
            $typeConfiguration['fieldsDefaultPublic'] = self::formatExpression($publicAnnotation->value);
339
        }
340
341 25
        $accessAnnotation = self::getFirstAnnotationMatching($graphClass->getAnnotations(), GQL\Access::class);
342 25
        if ($accessAnnotation) {
343 24
            $typeConfiguration['fieldsDefaultAccess'] = self::formatExpression($accessAnnotation->value);
344
        }
345
346 25
        return ['type' => $typeAnnotation->isRelay ? 'relay-mutation-payload' : 'object', 'config' => $typeConfiguration];
347
    }
348
349
    /**
350
     * Create a GraphQL Interface type configuration from annotations on properties.
351
     */
352 24
    private static function typeInterfaceAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\TypeInterface $interfaceAnnotation): array
353
    {
354 24
        $interfaceConfiguration = [];
355
356 24
        $fieldsFromProperties = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended());
357 24
        $fieldsFromMethods = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $graphClass->getMethods());
358
359 24
        $interfaceConfiguration['fields'] = array_merge($fieldsFromProperties, $fieldsFromMethods);
360 24
        $interfaceConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $interfaceConfiguration;
361
362 24
        $interfaceConfiguration['resolveType'] = self::formatExpression($interfaceAnnotation->resolveType);
363
364 24
        return ['type' => 'interface', 'config' => $interfaceConfiguration];
365
    }
366
367
    /**
368
     * Create a GraphQL Input type configuration from annotations on properties.
369
     */
370 24
    private static function inputAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Input $inputAnnotation): array
371
    {
372 24
        $inputConfiguration = array_merge([
373 24
            'fields' => self::getGraphQLInputFieldsFromAnnotations($graphClass, $graphClass->getPropertiesExtended()),
374 24
        ], self::getDescriptionConfiguration($graphClass->getAnnotations()));
375
376 24
        return ['type' => $inputAnnotation->isRelay ? 'relay-mutation-input' : 'input-object', 'config' => $inputConfiguration];
377
    }
378
379
    /**
380
     * Get a GraphQL scalar configuration from given scalar annotation.
381
     */
382 24
    private static function scalarAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Scalar $scalarAnnotation): array
383
    {
384 24
        $scalarConfiguration = [];
385
386 24
        if ($scalarAnnotation->scalarType) {
387 24
            $scalarConfiguration['scalarType'] = self::formatExpression($scalarAnnotation->scalarType);
388
        } else {
389
            $scalarConfiguration = [
390 24
                'serialize' => [$graphClass->getName(), 'serialize'],
391 24
                'parseValue' => [$graphClass->getName(), 'parseValue'],
392 24
                'parseLiteral' => [$graphClass->getName(), 'parseLiteral'],
393
            ];
394
        }
395
396 24
        $scalarConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $scalarConfiguration;
397
398 24
        return ['type' => 'custom-scalar', 'config' => $scalarConfiguration];
399
    }
400
401
    /**
402
     * Get a GraphQL Enum configuration from given enum annotation.
403
     */
404 24
    private static function enumAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Enum $enumAnnotation): array
405
    {
406 24
        $enumValues = $enumAnnotation->values ? $enumAnnotation->values : [];
407
408 24
        $values = [];
409
410 24
        foreach ($graphClass->getConstants() as $name => $value) {
411
            $valueAnnotation = current(array_filter($enumValues, function ($enumValueAnnotation) use ($name) {
412 24
                return $enumValueAnnotation->name == $name;
413 24
            }));
414 24
            $valueConfig = [];
415 24
            $valueConfig['value'] = $value;
416
417 24
            if ($valueAnnotation && $valueAnnotation->description) {
418 24
                $valueConfig['description'] = $valueAnnotation->description;
419
            }
420
421 24
            if ($valueAnnotation && $valueAnnotation->deprecationReason) {
422 24
                $valueConfig['deprecationReason'] = $valueAnnotation->deprecationReason;
423
            }
424
425 24
            $values[$name] = $valueConfig;
426
        }
427
428 24
        $enumConfiguration = ['values' => $values];
429 24
        $enumConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $enumConfiguration;
430
431 24
        return ['type' => 'enum', 'config' => $enumConfiguration];
432
    }
433
434
    /**
435
     * Get a GraphQL Union configuration from given union annotation.
436
     */
437 24
    private static function unionAnnotationToGQLConfiguration(GraphClass $graphClass, GQL\Union $unionAnnotation): array
438
    {
439 24
        $unionConfiguration = [];
440 24
        if (null !== $unionAnnotation->types) {
441 24
            $unionConfiguration['types'] = $unionAnnotation->types;
442
        } else {
443
            $types = array_keys(self::searchClassesMapBy(function ($gqlType, $configuration) use ($graphClass) {
444 24
                $typeClassName = $configuration['class'];
445 24
                $typeMetadata = self::getGraphClass($typeClassName);
446
447 24
                if ($graphClass->isInterface() && $typeMetadata->implementsInterface($graphClass->getName())) {
448 24
                    return true;
449
                }
450
451 24
                return $typeMetadata->isSubclassOf($graphClass->getName());
452 24
            }, self::GQL_TYPE));
453 24
            sort($types);
454 24
            $unionConfiguration['types'] = $types;
455
        }
456
457 24
        $unionConfiguration = self::getDescriptionConfiguration($graphClass->getAnnotations()) + $unionConfiguration;
458
459 24
        if ($unionAnnotation->resolveType) {
460 24
            $unionConfiguration['resolveType'] = self::formatExpression($unionAnnotation->resolveType);
461
        } else {
462 24
            if ($graphClass->hasMethod('resolveType')) {
463 24
                $method = $graphClass->getMethod('resolveType');
464 24
                if ($method->isStatic() && $method->isPublic()) {
465 24
                    $unionConfiguration['resolveType'] = self::formatExpression(sprintf("@=call('%s::%s', [service('overblog_graphql.type_resolver'), value], true)", self::formatNamespaceForExpression($graphClass->getName()), 'resolveType'));
466
                } else {
467 24
                    throw new InvalidArgumentException(sprintf('The "resolveType()" method on class must be static and public. Or you must define a "resolveType" attribute on the @Union annotation.'));
468
                }
469
            } else {
470 1
                throw new InvalidArgumentException(sprintf('The annotation @Union has no "resolveType" attribute and the related class has no "resolveType()" public static method. You need to define of them.'));
471
            }
472
        }
473
474 24
        return ['type' => 'union', 'config' => $unionConfiguration];
475
    }
476
477
    /**
478
     * @param ReflectionMethod|ReflectionProperty $reflector
479
     */
480 24
    private static function getTypeFieldConfigurationFromReflector(GraphClass $graphClass, Reflector $reflector, string $fieldAnnotationName = GQL\Field::class, string $currentValue = 'value'): array
481
    {
482 24
        $annotations = $graphClass->getAnnotations($reflector);
483
484 24
        $fieldAnnotation = self::getFirstAnnotationMatching($annotations, $fieldAnnotationName);
485 24
        $accessAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Access::class);
486 24
        $publicAnnotation = self::getFirstAnnotationMatching($annotations, GQL\IsPublic::class);
487
488 24
        $isMethod = $reflector instanceof ReflectionMethod;
489
490 24
        if (!$fieldAnnotation) {
491 24
            if ($accessAnnotation || $publicAnnotation) {
492 1
                throw new InvalidArgumentException(sprintf('The annotations "@Access" and/or "@Visible" defined on "%s" are only usable in addition of annotation "@Field"', $reflector->getName()));
493
            }
494
495 24
            return [];
496
        }
497
498 24
        if ($isMethod && !$reflector->isPublic()) {
499 1
            throw new InvalidArgumentException(sprintf('The Annotation "@Field" can only be applied to public method. The method "%s" is not public.', $reflector->getName()));
500
        }
501
502 24
        $fieldName = $reflector->getName();
503 24
        $fieldType = $fieldAnnotation->type;
504 24
        $fieldConfiguration = [];
505 24
        if ($fieldType) {
506 24
            $fieldConfiguration['type'] = $fieldType;
507
        }
508
509 24
        $fieldConfiguration = self::getDescriptionConfiguration($annotations, true) + $fieldConfiguration;
510
511 24
        $args = self::getArgs($fieldAnnotation->args, $isMethod && !$fieldAnnotation->argsBuilder ? $reflector : null);
512
513 24
        if (!empty($args)) {
514 24
            $fieldConfiguration['args'] = $args;
515
        }
516
517 24
        $fieldName = $fieldAnnotation->name ?: $fieldName;
518
519 24
        if ($fieldAnnotation->resolve) {
520 24
            $fieldConfiguration['resolve'] = self::formatExpression($fieldAnnotation->resolve);
521
        } else {
522 24
            if ($isMethod) {
523 24
                $fieldConfiguration['resolve'] = self::formatExpression(sprintf('call(%s.%s, %s)', $currentValue, $reflector->getName(), self::formatArgsForExpression($args)));
524
            } else {
525 24
                if ($fieldName !== $reflector->getName() || 'value' !== $currentValue) {
526
                    $fieldConfiguration['resolve'] = self::formatExpression(sprintf('%s.%s', $currentValue, $reflector->getName()));
527
                }
528
            }
529
        }
530
531 24
        if ($fieldAnnotation->argsBuilder) {
532 24
            if (is_string($fieldAnnotation->argsBuilder)) {
533
                $fieldConfiguration['argsBuilder'] = $fieldAnnotation->argsBuilder;
534 24
            } elseif (is_array($fieldAnnotation->argsBuilder)) {
535 24
                list($builder, $builderConfig) = $fieldAnnotation->argsBuilder;
536 24
                $fieldConfiguration['argsBuilder'] = ['builder' => $builder, 'config' => $builderConfig];
537
            } else {
538
                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()));
539
            }
540
        }
541
542 24
        if ($fieldAnnotation->fieldBuilder) {
543 24
            if (is_string($fieldAnnotation->fieldBuilder)) {
544
                $fieldConfiguration['builder'] = $fieldAnnotation->fieldBuilder;
545 24
            } elseif (is_array($fieldAnnotation->fieldBuilder)) {
546 24
                list($builder, $builderConfig) = $fieldAnnotation->fieldBuilder;
547 24
                $fieldConfiguration['builder'] = $builder;
548 24
                $fieldConfiguration['builderConfig'] = $builderConfig ?: [];
549
            } else {
550 24
                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()));
551
            }
552
        } else {
553 24
            if (!$fieldType) {
554 24
                if ($isMethod) {
555
                    /** @var ReflectionMethod $reflector */
556 24
                    if ($reflector->hasReturnType()) {
557
                        try {
558 24
                            $fieldConfiguration['type'] = self::resolveGraphQLTypeFromReflectionType($reflector->getReturnType(), self::VALID_OUTPUT_TYPES);
559
                        } catch (Exception $e) {
560 24
                            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()));
561
                        }
562
                    } else {
563 24
                        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()));
564
                    }
565
                } else {
566
                    try {
567 24
                        $fieldConfiguration['type'] = self::guessType($graphClass, $annotations);
568 2
                    } catch (Exception $e) {
569 2
                        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()));
570
                    }
571
                }
572
            }
573
        }
574
575 24
        if ($accessAnnotation) {
576 24
            $fieldConfiguration['access'] = self::formatExpression($accessAnnotation->value);
577
        }
578
579 24
        if ($publicAnnotation) {
580 24
            $fieldConfiguration['public'] = self::formatExpression($publicAnnotation->value);
581
        }
582
583 24
        if ($fieldAnnotation->complexity) {
584 24
            $fieldConfiguration['complexity'] = self::formatExpression($fieldAnnotation->complexity);
585
        }
586
587 24
        return [$fieldName => $fieldConfiguration];
588
    }
589
590
    /**
591
     * Create GraphQL input fields configuration based on annotations.
592
     *
593
     * @param ReflectionProperty[] $reflectors
594
     */
595 24
    private static function getGraphQLInputFieldsFromAnnotations(GraphClass $graphClass, array $reflectors): array
596
    {
597 24
        $fields = [];
598
599 24
        foreach ($reflectors as $reflector) {
600 24
            $annotations = $graphClass->getAnnotations($reflector);
601 24
            $fieldAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Field::class);
602
603
            // Ignore field with resolver when the type is an Input
604 24
            if ($fieldAnnotation->resolve) {
605
                return [];
606
            }
607
608 24
            $fieldName = $reflector->getName();
609 24
            $fieldType = $fieldAnnotation->type;
610 24
            $fieldConfiguration = [];
611 24
            if ($fieldType) {
612 24
                $resolvedType = self::resolveClassFromType($fieldType);
613
                // We found a type but it is not allowed
614 24
                if (null !== $resolvedType && !in_array($resolvedType['type'], self::VALID_INPUT_TYPES)) {
615
                    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']));
616
                }
617
618 24
                $fieldConfiguration['type'] = $fieldType;
619
            }
620
621 24
            $fieldConfiguration = array_merge(self::getDescriptionConfiguration($annotations, true), $fieldConfiguration);
622 24
            $fields[$fieldName] = $fieldConfiguration;
623
        }
624
625 24
        return $fields;
626
    }
627
628
    /**
629
     * Create GraphQL type fields configuration based on annotations.
630
     *
631
     * @param ReflectionProperty[]|ReflectionMethod[] $reflectors
632
     */
633 25
    private static function getGraphQLTypeFieldsFromAnnotations(GraphClass $graphClass, array $reflectors, string $fieldAnnotationName = GQL\Field::class, string $currentValue = 'value'): array
634
    {
635 25
        $fields = [];
636
637 25
        foreach ($reflectors as $reflector) {
638 24
            $fields = array_merge($fields, self::getTypeFieldConfigurationFromReflector($graphClass, $reflector, $fieldAnnotationName, $currentValue));
639
        }
640
641 25
        return $fields;
642
    }
643
644
    /**
645
     * Return fields config from Provider methods.
646
     * Loop through configured provider and extract fields targeting the targetType.
647
     */
648 25
    private static function getGraphQLFieldsFromProviders(GraphClass $graphClass, string $expectedAnnotation, string $targetType, bool $isDefaultTarget = false): array
649
    {
650 25
        $fields = [];
651 25
        foreach (self::$providers as ['metadata' => $providerMetadata, 'annotation' => $providerAnnotation]) {
652 24
            $defaultAccessAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\Access::class);
653 24
            $defaultIsPublicAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\IsPublic::class);
654
655 24
            $defaultAccess = $defaultAccessAnnotation ? self::formatExpression($defaultAccessAnnotation->value) : false;
656 24
            $defaultIsPublic = $defaultIsPublicAnnotation ? self::formatExpression($defaultIsPublicAnnotation->value) : false;
657
658 24
            $methods = [];
659
            // First found the methods matching the targeted type
660 24
            foreach ($providerMetadata->getMethods() as $method) {
661 24
                $annotations = $providerMetadata->getAnnotations($method);
662
663 24
                $annotation = self::getFirstAnnotationMatching($annotations, [GQL\Mutation::class, GQL\Query::class]);
664 24
                if (!$annotation) {
665
                    continue;
666
                }
667
668 24
                $annotationTarget = $annotation->targetType;
669 24
                if (!$annotationTarget && $isDefaultTarget) {
670 24
                    $annotationTarget = $targetType;
671 24
                    if (!($annotation instanceof $expectedAnnotation)) {
672 24
                        continue;
673
                    }
674
                }
675
676 24
                if ($annotationTarget !== $targetType) {
677 24
                    continue;
678
                }
679
680 24
                if (!($annotation instanceof $expectedAnnotation)) {
681 2
                    if (GQL\Mutation::class == $expectedAnnotation) {
682 1
                        $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);
683
                    } else {
684 1
                        $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);
685
                    }
686
687 2
                    throw new InvalidArgumentException($message);
688
                }
689 24
                $methods[$method->getName()] = $method;
690
            }
691
692 24
            $currentValue = sprintf("service('%s')", self::formatNamespaceForExpression($providerMetadata->getName()));
693 24
            $providerFields = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $methods, $expectedAnnotation, $currentValue);
694 24
            foreach ($providerFields as $fieldName => $fieldConfig) {
695 24
                if ($providerAnnotation->prefix) {
696 24
                    $fieldName = sprintf('%s%s', $providerAnnotation->prefix, $fieldName);
697
                }
698
699 24
                if ($defaultAccess && !isset($fieldConfig['access'])) {
700 24
                    $fieldConfig['access'] = $defaultAccess;
701
                }
702
703 24
                if ($defaultIsPublic && !isset($fieldConfig['public'])) {
704 24
                    $fieldConfig['public'] = $defaultIsPublic;
705
                }
706
707 24
                $fields[$fieldName] = $fieldConfig;
708
            }
709
        }
710
711 25
        return $fields;
712
    }
713
714
    /**
715
     * Get the config for description & deprecation reason.
716
     */
717 25
    private static function getDescriptionConfiguration(array $annotations, bool $withDeprecation = false): array
718
    {
719 25
        $config = [];
720 25
        $descriptionAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Description::class);
721 25
        if ($descriptionAnnotation) {
722 24
            $config['description'] = $descriptionAnnotation->value;
723
        }
724
725 25
        if ($withDeprecation) {
726 24
            $deprecatedAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Deprecated::class);
727 24
            if ($deprecatedAnnotation) {
728 24
                $config['deprecationReason'] = $deprecatedAnnotation->value;
729
            }
730
        }
731
732 25
        return $config;
733
    }
734
735
    /**
736
     * Get args config from an array of @Arg annotation or by auto-guessing if a method is provided.
737
     */
738 24
    private static function getArgs(?array $args, ReflectionMethod $method = null): array
739
    {
740 24
        $config = [];
741 24
        if (!empty($args)) {
742 24
            foreach ($args as $arg) {
743 24
                $config[$arg->name] = ['type' => $arg->type]
744 24
                    + ($arg->description ? ['description' => $arg->description] : [])
745 24
                    + ($arg->default ? ['defaultValue' => $arg->default] : []);
746
            }
747 24
        } elseif ($method) {
748 24
            $config = self::guessArgs($method);
749
        }
750
751 24
        return $config;
752
    }
753
754
    /**
755
     * Format an array of args to a list of arguments in an expression.
756
     */
757 24
    private static function formatArgsForExpression(array $args): string
758
    {
759 24
        $mapping = [];
760 24
        foreach ($args as $name => $config) {
761 24
            $mapping[] = sprintf('%s: "%s"', $name, $config['type']);
762
        }
763
764 24
        return sprintf('arguments({%s}, args)', implode(', ', $mapping));
765
    }
766
767
    /**
768
     * Format a namespace to be used in an expression (double escape).
769
     */
770 24
    private static function formatNamespaceForExpression(string $namespace): string
771
    {
772 24
        return str_replace('\\', '\\\\', $namespace);
773
    }
774
775
    /**
776
     * Get the first annotation matching given class.
777
     *
778
     * @param string|array $annotationClass
779
     *
780
     * @return mixed
781
     */
782 25
    private static function getFirstAnnotationMatching(array $annotations, $annotationClass)
783
    {
784 25
        if (is_string($annotationClass)) {
785 25
            $annotationClass = [$annotationClass];
786
        }
787
788 25
        foreach ($annotations as $annotation) {
789 25
            foreach ($annotationClass as $class) {
790 25
                if ($annotation instanceof $class) {
791 24
                    return $annotation;
792
                }
793
            }
794
        }
795
796 25
        return false;
797
    }
798
799
    /**
800
     * Format an expression (ie. add "@=" if not set).
801
     */
802 24
    private static function formatExpression(string $expression): string
803
    {
804 24
        return '@=' === substr($expression, 0, 2) ? $expression : sprintf('@=%s', $expression);
805
    }
806
807
    /**
808
     * Suffix a name if it is not already.
809
     */
810 24
    private static function suffixName(string $name, string $suffix): string
811
    {
812 24
        return substr($name, -strlen($suffix)) === $suffix ? $name : sprintf('%s%s', $name, $suffix);
813
    }
814
815
    /**
816
     * Try to guess a field type base on his annotations.
817
     *
818
     * @throws RuntimeException
819
     */
820 24
    private static function guessType(GraphClass $graphClass, array $annotations): string
821
    {
822 24
        $columnAnnotation = self::getFirstAnnotationMatching($annotations, Column::class);
823 24
        if ($columnAnnotation) {
824 24
            $type = self::resolveTypeFromDoctrineType($columnAnnotation->type);
825 24
            $nullable = $columnAnnotation->nullable;
826 24
            if ($type) {
827 24
                return $nullable ? $type : sprintf('%s!', $type);
828
            } else {
829 1
                throw new RuntimeException(sprintf('Unable to auto-guess GraphQL type from Doctrine type "%s"', $columnAnnotation->type));
830
            }
831
        }
832
833
        $associationAnnotations = [
834 24
            OneToMany::class => true,
835
            OneToOne::class => false,
836
            ManyToMany::class => true,
837
            ManyToOne::class => false,
838
        ];
839
840 24
        $associationAnnotation = self::getFirstAnnotationMatching($annotations, array_keys($associationAnnotations));
841 24
        if ($associationAnnotation) {
842 24
            $target = self::fullyQualifiedClassName($associationAnnotation->targetEntity, $graphClass->getNamespaceName());
843 24
            $type = self::resolveTypeFromClass($target, ['type']);
844
845 24
            if ($type) {
846 24
                $isMultiple = $associationAnnotations[get_class($associationAnnotation)];
847 24
                if ($isMultiple) {
848 24
                    return sprintf('[%s]!', $type);
849
                } else {
850 24
                    $isNullable = false;
851 24
                    $joinColumn = self::getFirstAnnotationMatching($annotations, JoinColumn::class);
852 24
                    if ($joinColumn) {
853 24
                        $isNullable = $joinColumn->nullable;
854
                    }
855
856 24
                    return sprintf('%s%s', $type, $isNullable ? '' : '!');
857
                }
858
            } else {
859 1
                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));
860
            }
861
        }
862
863
        throw new InvalidArgumentException(sprintf('No Doctrine ORM annotation found.'));
864
    }
865
866
    /**
867
     * Resolve a FQN from classname and namespace.
868
     *
869
     * @internal
870
     */
871 24
    public static function fullyQualifiedClassName(string $className, string $namespace): string
872
    {
873 24
        if (false === strpos($className, '\\') && $namespace) {
874 24
            return $namespace.'\\'.$className;
875
        }
876
877 1
        return $className;
878
    }
879
880
    /**
881
     * Resolve a GraphQLType from a doctrine type.
882
     */
883 24
    private static function resolveTypeFromDoctrineType(string $doctrineType): ?string
884
    {
885 24
        if (isset(self::$doctrineMapping[$doctrineType])) {
886 24
            return self::$doctrineMapping[$doctrineType];
887
        }
888
889
        switch ($doctrineType) {
890 24
            case 'integer':
891 24
            case 'smallint':
892 24
            case 'bigint':
893 24
                return 'Int';
894 24
            case 'string':
895 1
            case 'text':
896 24
                return 'String';
897 1
            case 'bool':
898 1
            case 'boolean':
899
                return 'Boolean';
900 1
            case 'float':
901 1
            case 'decimal':
902
                return 'Float';
903
            default:
904 1
                return null;
905
        }
906
    }
907
908
    /**
909
     * Transform a method arguments from reflection to a list of GraphQL argument.
910
     */
911 24
    private static function guessArgs(ReflectionMethod $method): array
912
    {
913 24
        $arguments = [];
914 24
        foreach ($method->getParameters() as $index => $parameter) {
915 24
            if (!$parameter->hasType()) {
916 1
                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()));
917
            }
918
919
            try {
920
                // @phpstan-ignore-next-line
921 24
                $gqlType = self::resolveGraphQLTypeFromReflectionType($parameter->getType(), self::VALID_INPUT_TYPES, $parameter->isDefaultValueAvailable());
922
            } catch (Exception $e) {
923
                throw new InvalidArgumentException(sprintf('Argument n°%s "$%s" on method "%s" cannot be auto-guessed : %s".', $index + 1, $parameter->getName(), $method->getName(), $e->getMessage()));
924
            }
925
926 24
            $argumentConfig = [];
927 24
            if ($parameter->isDefaultValueAvailable()) {
928 24
                $argumentConfig['defaultValue'] = $parameter->getDefaultValue();
929
            }
930
931 24
            $argumentConfig['type'] = $gqlType;
932
933 24
            $arguments[$parameter->getName()] = $argumentConfig;
934
        }
935
936 24
        return $arguments;
937
    }
938
939 24
    private static function resolveGraphQLTypeFromReflectionType(ReflectionNamedType $type, array $filterGraphQLTypes = [], bool $isOptional = false): string
940
    {
941 24
        $sType = $type->getName();
942 24
        if ($type->isBuiltin()) {
943 24
            $gqlType = self::resolveTypeFromPhpType($sType);
944 24
            if (null === $gqlType) {
945 24
                throw new RuntimeException(sprintf('No corresponding GraphQL type found for builtin type "%s"', $sType));
946
            }
947
        } else {
948 24
            $gqlType = self::resolveTypeFromClass($sType, $filterGraphQLTypes);
949 24
            if (null === $gqlType) {
950
                throw new RuntimeException(sprintf('No corresponding GraphQL %s found for class "%s"', $filterGraphQLTypes ? implode(',', $filterGraphQLTypes) : 'object', $sType));
951
            }
952
        }
953
954 24
        return sprintf('%s%s', $gqlType, ($type->allowsNull() || $isOptional) ? '' : '!');
955
    }
956
957
    /**
958
     * Resolve a GraphQL Type from a class name.
959
     */
960 24
    private static function resolveTypeFromClass(string $className, array $wantedTypes = []): ?string
961
    {
962 24
        foreach (self::$classesMap as $gqlType => $config) {
963 24
            if ($config['class'] === $className) {
964 24
                if (in_array($config['type'], $wantedTypes)) {
965 24
                    return $gqlType;
966
                }
967
            }
968
        }
969
970 1
        return null;
971
    }
972
973
    /**
974
     * Resolve a PHP class from a GraphQL type.
975
     *
976
     * @return string|array|null
977
     */
978 24
    private static function resolveClassFromType(string $type)
979
    {
980 24
        return self::$classesMap[$type] ?? null;
981
    }
982
983
    /**
984
     * Search the classes map for class by predicate.
985
     *
986
     * @return array
987
     */
988 25
    private static function searchClassesMapBy(callable $predicate, string $type = null)
989
    {
990 25
        $classNames = [];
991 25
        foreach (self::$classesMap as $gqlType => $config) {
992 25
            if ($type && $config['type'] !== $type) {
993 25
                continue;
994
            }
995
996 24
            if ($predicate($gqlType, $config)) {
997 24
                $classNames[$gqlType] = $config;
998
            }
999
        }
1000
1001 25
        return $classNames;
1002
    }
1003
1004
    /**
1005
     * Convert a PHP Builtin type to a GraphQL type.
1006
     */
1007 24
    private static function resolveTypeFromPhpType(string $phpType): ?string
1008
    {
1009
        switch ($phpType) {
1010 24
            case 'boolean':
1011 24
            case 'bool':
1012 24
                return 'Boolean';
1013 24
            case 'integer':
1014 24
            case 'int':
1015 24
                return 'Int';
1016 24
            case 'float':
1017 24
            case 'double':
1018 24
                return 'Float';
1019 24
            case 'string':
1020 24
                return 'String';
1021
            default:
1022
                return null;
1023
        }
1024
    }
1025
}
1026