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

Passed
Pull Request — master (#710)
by Vincent
24:34
created

scalarAnnotationToGQLConfiguration()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

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