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
Push — master ( 50f85e...7d433d )
by Vincent
28s queued 12s
created

unionAnnotationToGQLConfiguration()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 38
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 8

Importance

Changes 0
Metric Value
eloc 26
c 0
b 0
f 0
dl 0
loc 38
ccs 22
cts 22
cp 1
rs 8.4444
cc 8
nc 8
nop 2
crap 8
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
        if (!$fieldAnnotation) {
489 24
            if ($accessAnnotation || $publicAnnotation) {
490 1
                throw new InvalidArgumentException(sprintf('The annotations "@Access" and/or "@Visible" defined on "%s" are only usable in addition of annotation "@Field"', $reflector->getName()));
491
            }
492
493 24
            return [];
494
        }
495
496 24
        if ($reflector instanceof ReflectionMethod && !$reflector->isPublic()) {
497 1
            throw new InvalidArgumentException(sprintf('The Annotation "@Field" can only be applied to public method. The method "%s" is not public.', $reflector->getName()));
498
        }
499
500 24
        $fieldName = $reflector->getName();
501 24
        $fieldType = $fieldAnnotation->type;
502 24
        $fieldConfiguration = [];
503 24
        if ($fieldType) {
504 24
            $fieldConfiguration['type'] = $fieldType;
505
        }
506
507 24
        $fieldConfiguration = self::getDescriptionConfiguration($annotations, true) + $fieldConfiguration;
508
509 24
        $args = [];
510 24
        if (!empty($fieldAnnotation->args)) {
511 24
            foreach ($fieldAnnotation->args as $arg) {
512 24
                $args[$arg->name] = ['type' => $arg->type]
513 24
                    + ($arg->description ? ['description' => $arg->description] : [])
514 24
                    + ($arg->default ? ['defaultValue' => $arg->default] : []);
515
            }
516 24
        } elseif ($reflector instanceof ReflectionMethod) {
517 24
            $args = self::guessArgs($reflector);
518
        }
519
520 24
        if (!empty($args)) {
521 24
            $fieldConfiguration['args'] = $args;
522
        }
523
524 24
        $fieldName = $fieldAnnotation->name ?: $fieldName;
525
526 24
        if ($fieldAnnotation->resolve) {
527 24
            $fieldConfiguration['resolve'] = self::formatExpression($fieldAnnotation->resolve);
528
        } else {
529 24
            if ($reflector instanceof ReflectionMethod) {
530 24
                $fieldConfiguration['resolve'] = self::formatExpression(sprintf('call(%s.%s, %s)', $currentValue, $reflector->getName(), self::formatArgsForExpression($args)));
531
            } else {
532 24
                if ($fieldName !== $reflector->getName() || 'value' !== $currentValue) {
533
                    $fieldConfiguration['resolve'] = self::formatExpression(sprintf('%s.%s', $currentValue, $reflector->getName()));
534
                }
535
            }
536
        }
537
538 24
        if ($fieldAnnotation->argsBuilder) {
539 24
            if (is_string($fieldAnnotation->argsBuilder)) {
540
                $fieldConfiguration['argsBuilder'] = $fieldAnnotation->argsBuilder;
541 24
            } elseif (is_array($fieldAnnotation->argsBuilder)) {
542 24
                list($builder, $builderConfig) = $fieldAnnotation->argsBuilder;
543 24
                $fieldConfiguration['argsBuilder'] = ['builder' => $builder, 'config' => $builderConfig];
544
            } else {
545
                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()));
546
            }
547
        }
548
549 24
        if ($fieldAnnotation->fieldBuilder) {
550 24
            if (is_string($fieldAnnotation->fieldBuilder)) {
551
                $fieldConfiguration['builder'] = $fieldAnnotation->fieldBuilder;
552 24
            } elseif (is_array($fieldAnnotation->fieldBuilder)) {
553 24
                list($builder, $builderConfig) = $fieldAnnotation->fieldBuilder;
554 24
                $fieldConfiguration['builder'] = $builder;
555 24
                $fieldConfiguration['builderConfig'] = $builderConfig ?: [];
556
            } else {
557 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()));
558
            }
559
        } else {
560 24
            if (!$fieldType) {
561 24
                if ($reflector instanceof ReflectionMethod) {
562
                    /** @var ReflectionMethod $reflector */
563 24
                    if ($reflector->hasReturnType()) {
564
                        try {
565
                            // @phpstan-ignore-next-line
566 24
                            $fieldConfiguration['type'] = self::resolveGraphQLTypeFromReflectionType($reflector->getReturnType(), self::VALID_OUTPUT_TYPES);
567
                        } catch (Exception $e) {
568 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()));
569
                        }
570
                    } else {
571 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()));
572
                    }
573
                } else {
574
                    try {
575 24
                        $fieldConfiguration['type'] = self::guessType($graphClass, $annotations);
576 2
                    } catch (Exception $e) {
577 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()));
578
                    }
579
                }
580
            }
581
        }
582
583 24
        if ($accessAnnotation) {
584 24
            $fieldConfiguration['access'] = self::formatExpression($accessAnnotation->value);
585
        }
586
587 24
        if ($publicAnnotation) {
588 24
            $fieldConfiguration['public'] = self::formatExpression($publicAnnotation->value);
589
        }
590
591 24
        if ($fieldAnnotation->complexity) {
592 24
            $fieldConfiguration['complexity'] = self::formatExpression($fieldAnnotation->complexity);
593
        }
594
595 24
        return [$fieldName => $fieldConfiguration];
596
    }
597
598
    /**
599
     * Create GraphQL input fields configuration based on annotations.
600
     *
601
     * @param ReflectionProperty[] $reflectors
602
     */
603 24
    private static function getGraphQLInputFieldsFromAnnotations(GraphClass $graphClass, array $reflectors): array
604
    {
605 24
        $fields = [];
606
607 24
        foreach ($reflectors as $reflector) {
608 24
            $annotations = $graphClass->getAnnotations($reflector);
609 24
            $fieldAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Field::class);
610
611
            // Ignore field with resolver when the type is an Input
612 24
            if ($fieldAnnotation->resolve) {
613
                return [];
614
            }
615
616 24
            $fieldName = $reflector->getName();
617 24
            $fieldType = $fieldAnnotation->type;
618 24
            $fieldConfiguration = [];
619 24
            if ($fieldType) {
620 24
                $resolvedType = self::resolveClassFromType($fieldType);
621
                // We found a type but it is not allowed
622 24
                if (null !== $resolvedType && !in_array($resolvedType['type'], self::VALID_INPUT_TYPES)) {
623
                    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']));
624
                }
625
626 24
                $fieldConfiguration['type'] = $fieldType;
627
            }
628
629 24
            $fieldConfiguration = array_merge(self::getDescriptionConfiguration($annotations, true), $fieldConfiguration);
630 24
            $fields[$fieldName] = $fieldConfiguration;
631
        }
632
633 24
        return $fields;
634
    }
635
636
    /**
637
     * Create GraphQL type fields configuration based on annotations.
638
     *
639
     * @param ReflectionProperty[]|ReflectionMethod[] $reflectors
640
     */
641 25
    private static function getGraphQLTypeFieldsFromAnnotations(GraphClass $graphClass, array $reflectors, string $fieldAnnotationName = GQL\Field::class, string $currentValue = 'value'): array
642
    {
643 25
        $fields = [];
644
645 25
        foreach ($reflectors as $reflector) {
646 24
            $fields = array_merge($fields, self::getTypeFieldConfigurationFromReflector($graphClass, $reflector, $fieldAnnotationName, $currentValue));
647
        }
648
649 25
        return $fields;
650
    }
651
652
    /**
653
     * Return fields config from Provider methods.
654
     * Loop through configured provider and extract fields targeting the targetType.
655
     */
656 25
    private static function getGraphQLFieldsFromProviders(GraphClass $graphClass, string $expectedAnnotation, string $targetType, bool $isDefaultTarget = false): array
657
    {
658 25
        $fields = [];
659 25
        foreach (self::$providers as ['metadata' => $providerMetadata, 'annotation' => $providerAnnotation]) {
660 24
            $defaultAccessAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\Access::class);
661 24
            $defaultIsPublicAnnotation = self::getFirstAnnotationMatching($providerMetadata->getAnnotations(), GQL\IsPublic::class);
662
663 24
            $defaultAccess = $defaultAccessAnnotation ? self::formatExpression($defaultAccessAnnotation->value) : false;
664 24
            $defaultIsPublic = $defaultIsPublicAnnotation ? self::formatExpression($defaultIsPublicAnnotation->value) : false;
665
666 24
            $methods = [];
667
            // First found the methods matching the targeted type
668 24
            foreach ($providerMetadata->getMethods() as $method) {
669 24
                $annotations = $providerMetadata->getAnnotations($method);
670
671 24
                $annotation = self::getFirstAnnotationMatching($annotations, [GQL\Mutation::class, GQL\Query::class]);
672 24
                if (!$annotation) {
673
                    continue;
674
                }
675
676 24
                $annotationTarget = $annotation->targetType;
677 24
                if (!$annotationTarget && $isDefaultTarget) {
678 24
                    $annotationTarget = $targetType;
679 24
                    if (!($annotation instanceof $expectedAnnotation)) {
680 24
                        continue;
681
                    }
682
                }
683
684 24
                if ($annotationTarget !== $targetType) {
685 24
                    continue;
686
                }
687
688 24
                if (!($annotation instanceof $expectedAnnotation)) {
689 2
                    if (GQL\Mutation::class == $expectedAnnotation) {
690 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);
691
                    } else {
692 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);
693
                    }
694
695 2
                    throw new InvalidArgumentException($message);
696
                }
697 24
                $methods[$method->getName()] = $method;
698
            }
699
700 24
            $currentValue = sprintf("service('%s')", self::formatNamespaceForExpression($providerMetadata->getName()));
701 24
            $providerFields = self::getGraphQLTypeFieldsFromAnnotations($graphClass, $methods, $expectedAnnotation, $currentValue);
702 24
            foreach ($providerFields as $fieldName => $fieldConfig) {
703 24
                if ($providerAnnotation->prefix) {
704 24
                    $fieldName = sprintf('%s%s', $providerAnnotation->prefix, $fieldName);
705
                }
706
707 24
                if ($defaultAccess && !isset($fieldConfig['access'])) {
708 24
                    $fieldConfig['access'] = $defaultAccess;
709
                }
710
711 24
                if ($defaultIsPublic && !isset($fieldConfig['public'])) {
712 24
                    $fieldConfig['public'] = $defaultIsPublic;
713
                }
714
715 24
                $fields[$fieldName] = $fieldConfig;
716
            }
717
        }
718
719 25
        return $fields;
720
    }
721
722
    /**
723
     * Get the config for description & deprecation reason.
724
     */
725 25
    private static function getDescriptionConfiguration(array $annotations, bool $withDeprecation = false): array
726
    {
727 25
        $config = [];
728 25
        $descriptionAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Description::class);
729 25
        if ($descriptionAnnotation) {
730 24
            $config['description'] = $descriptionAnnotation->value;
731
        }
732
733 25
        if ($withDeprecation) {
734 24
            $deprecatedAnnotation = self::getFirstAnnotationMatching($annotations, GQL\Deprecated::class);
735 24
            if ($deprecatedAnnotation) {
736 24
                $config['deprecationReason'] = $deprecatedAnnotation->value;
737
            }
738
        }
739
740 25
        return $config;
741
    }
742
743
    /**
744
     * Format an array of args to a list of arguments in an expression.
745
     */
746 24
    private static function formatArgsForExpression(array $args): string
747
    {
748 24
        $mapping = [];
749 24
        foreach ($args as $name => $config) {
750 24
            $mapping[] = sprintf('%s: "%s"', $name, $config['type']);
751
        }
752
753 24
        return sprintf('arguments({%s}, args)', implode(', ', $mapping));
754
    }
755
756
    /**
757
     * Format a namespace to be used in an expression (double escape).
758
     */
759 24
    private static function formatNamespaceForExpression(string $namespace): string
760
    {
761 24
        return str_replace('\\', '\\\\', $namespace);
762
    }
763
764
    /**
765
     * Get the first annotation matching given class.
766
     *
767
     * @param string|array $annotationClass
768
     *
769
     * @return mixed
770
     */
771 25
    private static function getFirstAnnotationMatching(array $annotations, $annotationClass)
772
    {
773 25
        if (is_string($annotationClass)) {
774 25
            $annotationClass = [$annotationClass];
775
        }
776
777 25
        foreach ($annotations as $annotation) {
778 25
            foreach ($annotationClass as $class) {
779 25
                if ($annotation instanceof $class) {
780 24
                    return $annotation;
781
                }
782
            }
783
        }
784
785 25
        return false;
786
    }
787
788
    /**
789
     * Format an expression (ie. add "@=" if not set).
790
     */
791 24
    private static function formatExpression(string $expression): string
792
    {
793 24
        return '@=' === substr($expression, 0, 2) ? $expression : sprintf('@=%s', $expression);
794
    }
795
796
    /**
797
     * Suffix a name if it is not already.
798
     */
799 24
    private static function suffixName(string $name, string $suffix): string
800
    {
801 24
        return substr($name, -strlen($suffix)) === $suffix ? $name : sprintf('%s%s', $name, $suffix);
802
    }
803
804
    /**
805
     * Try to guess a field type base on his annotations.
806
     *
807
     * @throws RuntimeException
808
     */
809 24
    private static function guessType(GraphClass $graphClass, array $annotations): string
810
    {
811 24
        $columnAnnotation = self::getFirstAnnotationMatching($annotations, Column::class);
812 24
        if ($columnAnnotation) {
813 24
            $type = self::resolveTypeFromDoctrineType($columnAnnotation->type);
814 24
            $nullable = $columnAnnotation->nullable;
815 24
            if ($type) {
816 24
                return $nullable ? $type : sprintf('%s!', $type);
817
            } else {
818 1
                throw new RuntimeException(sprintf('Unable to auto-guess GraphQL type from Doctrine type "%s"', $columnAnnotation->type));
819
            }
820
        }
821
822
        $associationAnnotations = [
823 24
            OneToMany::class => true,
824
            OneToOne::class => false,
825
            ManyToMany::class => true,
826
            ManyToOne::class => false,
827
        ];
828
829 24
        $associationAnnotation = self::getFirstAnnotationMatching($annotations, array_keys($associationAnnotations));
830 24
        if ($associationAnnotation) {
831 24
            $target = self::fullyQualifiedClassName($associationAnnotation->targetEntity, $graphClass->getNamespaceName());
832 24
            $type = self::resolveTypeFromClass($target, ['type']);
833
834 24
            if ($type) {
835 24
                $isMultiple = $associationAnnotations[get_class($associationAnnotation)];
836 24
                if ($isMultiple) {
837 24
                    return sprintf('[%s]!', $type);
838
                } else {
839 24
                    $isNullable = false;
840 24
                    $joinColumn = self::getFirstAnnotationMatching($annotations, JoinColumn::class);
841 24
                    if ($joinColumn) {
842 24
                        $isNullable = $joinColumn->nullable;
843
                    }
844
845 24
                    return sprintf('%s%s', $type, $isNullable ? '' : '!');
846
                }
847
            } else {
848 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));
849
            }
850
        }
851
852
        throw new InvalidArgumentException(sprintf('No Doctrine ORM annotation found.'));
853
    }
854
855
    /**
856
     * Resolve a FQN from classname and namespace.
857
     *
858
     * @internal
859
     */
860 24
    public static function fullyQualifiedClassName(string $className, string $namespace): string
861
    {
862 24
        if (false === strpos($className, '\\') && $namespace) {
863 24
            return $namespace.'\\'.$className;
864
        }
865
866 1
        return $className;
867
    }
868
869
    /**
870
     * Resolve a GraphQLType from a doctrine type.
871
     */
872 24
    private static function resolveTypeFromDoctrineType(string $doctrineType): ?string
873
    {
874 24
        if (isset(self::$doctrineMapping[$doctrineType])) {
875 24
            return self::$doctrineMapping[$doctrineType];
876
        }
877
878
        switch ($doctrineType) {
879 24
            case 'integer':
880 24
            case 'smallint':
881 24
            case 'bigint':
882 24
                return 'Int';
883 24
            case 'string':
884 1
            case 'text':
885 24
                return 'String';
886 1
            case 'bool':
887 1
            case 'boolean':
888
                return 'Boolean';
889 1
            case 'float':
890 1
            case 'decimal':
891
                return 'Float';
892
            default:
893 1
                return null;
894
        }
895
    }
896
897
    /**
898
     * Transform a method arguments from reflection to a list of GraphQL argument.
899
     */
900 24
    private static function guessArgs(ReflectionMethod $method): array
901
    {
902 24
        $arguments = [];
903 24
        foreach ($method->getParameters() as $index => $parameter) {
904 24
            if (!$parameter->hasType()) {
905 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()));
906
            }
907
908
            try {
909
                // @phpstan-ignore-next-line
910 24
                $gqlType = self::resolveGraphQLTypeFromReflectionType($parameter->getType(), self::VALID_INPUT_TYPES, $parameter->isDefaultValueAvailable());
911
            } catch (Exception $e) {
912
                throw new InvalidArgumentException(sprintf('Argument n°%s "$%s" on method "%s" cannot be auto-guessed : %s".', $index + 1, $parameter->getName(), $method->getName(), $e->getMessage()));
913
            }
914
915 24
            $argumentConfig = [];
916 24
            if ($parameter->isDefaultValueAvailable()) {
917 24
                $argumentConfig['defaultValue'] = $parameter->getDefaultValue();
918
            }
919
920 24
            $argumentConfig['type'] = $gqlType;
921
922 24
            $arguments[$parameter->getName()] = $argumentConfig;
923
        }
924
925 24
        return $arguments;
926
    }
927
928 24
    private static function resolveGraphQLTypeFromReflectionType(ReflectionNamedType $type, array $filterGraphQLTypes = [], bool $isOptional = false): string
929
    {
930 24
        $sType = $type->getName();
931 24
        if ($type->isBuiltin()) {
932 24
            $gqlType = self::resolveTypeFromPhpType($sType);
933 24
            if (null === $gqlType) {
934 24
                throw new RuntimeException(sprintf('No corresponding GraphQL type found for builtin type "%s"', $sType));
935
            }
936
        } else {
937 24
            $gqlType = self::resolveTypeFromClass($sType, $filterGraphQLTypes);
938 24
            if (null === $gqlType) {
939
                throw new RuntimeException(sprintf('No corresponding GraphQL %s found for class "%s"', $filterGraphQLTypes ? implode(',', $filterGraphQLTypes) : 'object', $sType));
940
            }
941
        }
942
943 24
        return sprintf('%s%s', $gqlType, ($type->allowsNull() || $isOptional) ? '' : '!');
944
    }
945
946
    /**
947
     * Resolve a GraphQL Type from a class name.
948
     */
949 24
    private static function resolveTypeFromClass(string $className, array $wantedTypes = []): ?string
950
    {
951 24
        foreach (self::$classesMap as $gqlType => $config) {
952 24
            if ($config['class'] === $className) {
953 24
                if (in_array($config['type'], $wantedTypes)) {
954 24
                    return $gqlType;
955
                }
956
            }
957
        }
958
959 1
        return null;
960
    }
961
962
    /**
963
     * Resolve a PHP class from a GraphQL type.
964
     *
965
     * @return string|array|null
966
     */
967 24
    private static function resolveClassFromType(string $type)
968
    {
969 24
        return self::$classesMap[$type] ?? null;
970
    }
971
972
    /**
973
     * Search the classes map for class by predicate.
974
     *
975
     * @return array
976
     */
977 25
    private static function searchClassesMapBy(callable $predicate, string $type = null)
978
    {
979 25
        $classNames = [];
980 25
        foreach (self::$classesMap as $gqlType => $config) {
981 25
            if ($type && $config['type'] !== $type) {
982 25
                continue;
983
            }
984
985 24
            if ($predicate($gqlType, $config)) {
986 24
                $classNames[$gqlType] = $config;
987
            }
988
        }
989
990 25
        return $classNames;
991
    }
992
993
    /**
994
     * Convert a PHP Builtin type to a GraphQL type.
995
     */
996 24
    private static function resolveTypeFromPhpType(string $phpType): ?string
997
    {
998
        switch ($phpType) {
999 24
            case 'boolean':
1000 24
            case 'bool':
1001 24
                return 'Boolean';
1002 24
            case 'integer':
1003 24
            case 'int':
1004 24
                return 'Int';
1005 24
            case 'float':
1006 24
            case 'double':
1007 24
                return 'Float';
1008 24
            case 'string':
1009 24
                return 'String';
1010
            default:
1011
                return null;
1012
        }
1013
    }
1014
}
1015