Scrutinizer GitHub App not installed

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

Install GitHub App

Completed
Pull Request — annotations (#407)
by Vincent
126:18
created

AnnotationParser::getGraphqlInputType()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
ccs 7
cts 8
cp 0.875
rs 9.7998
cc 3
nc 3
nop 4
crap 3.0175
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Overblog\GraphQLBundle\Config\Parser;
6
7
use Doctrine\Common\Annotations\AnnotationReader;
8
use Doctrine\Common\Annotations\AnnotationRegistry;
9
use Overblog\GraphQLBundle\Annotation\Enum as AnnotationEnum;
10
use Overblog\GraphQLBundle\Annotation\InputType as AnnotationInputType;
11
use Overblog\GraphQLBundle\Annotation\Scalar as AnnotationScalar;
12
use Overblog\GraphQLBundle\Annotation\Type as AnnotationType;
13
use Overblog\GraphQLBundle\Annotation\TypeInterface as AnnotationInterface;
14
use Overblog\GraphQLBundle\Annotation\Union as AnnotationUnion;
15
use Symfony\Component\Config\Resource\FileResource;
16
use Symfony\Component\DependencyInjection\ContainerBuilder;
17
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
18
19
class AnnotationParser implements PreParserInterface
20
{
21
    private static $annotationReader = null;
22
    private static $classesMap = [];
23
24
    /**
25
     * {@inheritdoc}
26
     *
27
     * @throws \ReflectionException
28
     * @throws InvalidArgumentException
29
     */
30 14
    public static function parse(\SplFileInfo $file, ContainerBuilder $container): array
31
    {
32 14
        return self::proccessFile($file, $container);
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     *
38
     * @throws \ReflectionException
39
     * @throws InvalidArgumentException
40
     */
41 1
    public static function preParse(\SplFileInfo $file, ContainerBuilder $container): void
42
    {
43 1
        self::proccessFile($file, $container, true);
44 1
    }
45
46
    /**
47
     * Process a file.
48
     *
49
     * @param \SplFileInfo     $file
50
     * @param ContainerBuilder $container
51
     * @param bool             $resolveClassMap
52
     *
53
     * @throws \ReflectionException
54
     * @throws InvalidArgumentException
55
     */
56 14
    public static function proccessFile(\SplFileInfo $file, ContainerBuilder $container, bool $resolveClassMap = false): array
57
    {
58 14
        $container->addResource(new FileResource($file->getRealPath()));
59
        try {
60 14
            $fileContent = \file_get_contents($file->getRealPath());
61
62 14
            $shortClassName = \substr($file->getFilename(), 0, -4);
63 14
            if (\preg_match('#namespace (.+);#', $fileContent, $namespace)) {
64 14
                $className = $namespace[1].'\\'.$shortClassName;
65 14
                $namespace = $namespace[1];
66
            } else {
67
                $className = $shortClassName;
68
            }
69
70 14
            $reflexionEntity = new \ReflectionClass($className);
71
72 14
            $classAnnotations = self::getAnnotationReader()->getClassAnnotations($reflexionEntity);
73
74 14
            $properties = $reflexionEntity->getProperties();
75
76 14
            $propertiesAnnotations = [];
77 14
            foreach ($properties as $property) {
78 9
                $propertiesAnnotations[$property->getName()] = self::getAnnotationReader()->getPropertyAnnotations($property);
79
            }
80
81 14
            $methods = $reflexionEntity->getMethods();
82 14
            $methodsAnnotations = [];
83 14
            foreach ($methods as $method) {
84 3
                $methodsAnnotations[$method->getName()] = self::getAnnotationReader()->getMethodAnnotations($method);
0 ignored issues
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
85
            }
86
87 14
            $gqlTypes = [];
88
89 14
            foreach ($classAnnotations as $classAnnotation) {
90 14
                $gqlName = $gqlConfiguration = $gqlType = false;
91
                switch (true) {
92 14
                    case $classAnnotation instanceof AnnotationType:
93 8
                        $gqlType = 'type';
94 8
                        if (!$resolveClassMap) {
95 8
                            $gqlConfiguration = self::getGraphqlType($classAnnotation, $classAnnotations, $propertiesAnnotations, $methodsAnnotations, $namespace);
0 ignored issues
show
Bug introduced by
It seems like $namespace can also be of type array<integer,string>; however, Overblog\GraphQLBundle\C...arser::getGraphqlType() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
96
                        }
97 8
                        break;
98 10 View Code Duplication
                    case $classAnnotation instanceof AnnotationInputType:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99 1
                        $gqlType = 'input';
100 1
                        $gqlName = $classAnnotation->name ?: self::suffixName($shortClassName, 'Input');
101 1
                        if (!$resolveClassMap) {
102 1
                            $gqlConfiguration = self::getGraphqlInputType($classAnnotation, $classAnnotations, $propertiesAnnotations, $namespace);
0 ignored issues
show
Bug introduced by
It seems like $namespace can also be of type array<integer,string>; however, Overblog\GraphQLBundle\C...::getGraphqlInputType() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
103
                        }
104 1
                        break;
105 10
                    case $classAnnotation instanceof AnnotationScalar:
106 2
                        $gqlType = 'scalar';
107 2
                        if (!$resolveClassMap) {
108 2
                            $gqlConfiguration = self::getGraphqlScalar($className, $classAnnotation, $classAnnotations);
109
                        }
110 2
                        break;
111 9 View Code Duplication
                    case $classAnnotation instanceof AnnotationEnum:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112 1
                        $gqlType = 'enum';
113 1
                        $gqlName = $classAnnotation->name ?: self::suffixName($shortClassName, 'Enum');
114 1
                        if (!$resolveClassMap) {
115 1
                            $gqlConfiguration = self::getGraphqlEnum($classAnnotation, $classAnnotations, $reflexionEntity->getConstants());
116
                        }
117 1
                        break;
118 9
                    case $classAnnotation instanceof AnnotationUnion:
119 1
                        $gqlType = 'union';
120 1
                        if (!$resolveClassMap) {
121 1
                            $gqlConfiguration = self::getGraphqlUnion($classAnnotation, $classAnnotations);
122
                        }
123 1
                        break;
124 9
                    case $classAnnotation instanceof AnnotationInterface:
125 1
                        $gqlType = 'interface';
126 1
                        if (!$resolveClassMap) {
127 1
                            $gqlConfiguration = self::getGraphqlInterface($classAnnotation, $classAnnotations, $propertiesAnnotations, $methodsAnnotations, $namespace);
0 ignored issues
show
Bug introduced by
It seems like $namespace can also be of type array<integer,string>; however, Overblog\GraphQLBundle\C...::getGraphqlInterface() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
128
                        }
129 1
                        break;
130
                }
131
132 14
                if ($gqlType) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $gqlType of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
133 14
                    if (!$gqlName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $gqlName of type false|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
134 12
                        $gqlName = $classAnnotation->name ?: $shortClassName;
135
                    }
136 14
                    if ($resolveClassMap) {
137 1
                        if (isset(self::$classesMap[$gqlName])) {
138
                            throw new InvalidArgumentException(\sprintf('The GraphQL type "%s" has already been registered in class "%s"', $gqlName, self::$classesMap[$gqlName]['class']));
139
                        }
140 1
                        self::$classesMap[$gqlName] = ['type' => $gqlType, 'class' => $className];
141
                    } else {
142 14
                        $gqlTypes += [$gqlName => $gqlConfiguration];
143
                    }
144
                }
145
            }
146
147 14
            return $resolveClassMap ? self::$classesMap : $gqlTypes;
148
        } catch (\InvalidArgumentException $e) {
149
            throw new InvalidArgumentException(\sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e);
150
        }
151
    }
152
153
    /**
154
     * Retrieve annotation reader.
155
     *
156
     * @return AnnotationReader
157
     */
158 14
    private static function getAnnotationReader()
159
    {
160 14
        if (null === self::$annotationReader) {
161 1
            if (!\class_exists('\\Doctrine\\Common\\Annotations\\AnnotationReader') ||
162 1
                !\class_exists('\\Doctrine\\Common\\Annotations\\AnnotationRegistry')) {
163
                throw new \Exception('In order to use graphql annotation, you need to require doctrine annotations');
164
            }
165
166 1
            AnnotationRegistry::registerLoader('class_exists');
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\Common\Annotati...istry::registerLoader() has been deprecated with message: this method is deprecated and will be removed in doctrine/annotations 2.0 autoloading should be deferred to the globally registered autoloader by then. For now, use @example AnnotationRegistry::registerLoader('class_exists')

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
167 1
            self::$annotationReader = new AnnotationReader();
168
        }
169
170 14
        return self::$annotationReader;
171
    }
172
173
    /**
174
     * Create a GraphQL Type configuration from annotations on class, properties and methods.
175
     *
176
     * @param AnnotationType $typeAnnotation
177
     * @param array          $classAnnotations
178
     * @param array          $propertiesAnnotations
179
     * @param array          $methodsAnnotations
180
     * @param string         $namespace
181
     *
182
     * @return array
183
     */
184 8
    private static function getGraphqlType(AnnotationType $typeAnnotation, array $classAnnotations, array $propertiesAnnotations, array $methodsAnnotations, string $namespace)
185
    {
186 8
        $typeConfiguration = [];
187
188 8
        $fields = self::getGraphqlFieldsFromAnnotations($namespace, $propertiesAnnotations);
189 8
        $fields += self::getGraphqlFieldsFromAnnotations($namespace, $methodsAnnotations, false, true);
190
191 8
        if (empty($fields)) {
192
            return [];
193
        }
194
195 8
        $typeConfiguration['fields'] = $fields;
196
197 8
        $publicAnnotation = self::getFirstAnnotationMatching($classAnnotations, 'Overblog\GraphQLBundle\Annotation\IsPublic');
198 8
        if ($publicAnnotation) {
199 1
            $typeConfiguration['fieldsDefaultPublic'] = self::formatExpression($publicAnnotation->value);
200
        }
201
202 8
        $accessAnnotation = self::getFirstAnnotationMatching($classAnnotations, 'Overblog\GraphQLBundle\Annotation\Access');
203 8
        if ($accessAnnotation) {
204 1
            $typeConfiguration['fieldsDefaultAccess'] = self::formatExpression($accessAnnotation->value);
205
        }
206
207 8
        $typeConfiguration += self::getDescriptionConfiguration($classAnnotations);
208 8
        if ($typeAnnotation->interfaces) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $typeAnnotation->interfaces of type string[] 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...
209
            $typeConfiguration['interfaces'] = $typeAnnotation->interfaces;
210
        }
211
212 8
        return ['type' => $typeAnnotation->isRelay ? 'relay-mutation-payload' : 'object', 'config' => $typeConfiguration];
213
    }
214
215
    /**
216
     * Create a GraphQL Interface type configuration from annotations on properties.
217
     *
218
     * @param string              $shortClassName
0 ignored issues
show
Bug introduced by
There is no parameter named $shortClassName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
219
     * @param AnnotationInterface $interfaceAnnotation
220
     * @param array               $propertiesAnnotations
221
     * @param string              $namespace
222
     *
223
     * @return array
224
     */
225 1
    private static function getGraphqlInterface(AnnotationInterface $interfaceAnnotation, array $classAnnotations, array $propertiesAnnotations, array $methodsAnnotations, string $namespace)
0 ignored issues
show
Unused Code introduced by
The parameter $interfaceAnnotation is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
226
    {
227 1
        $interfaceConfiguration = [];
228
229 1
        $fields = self::getGraphqlFieldsFromAnnotations($namespace, $propertiesAnnotations);
230 1
        $fields += self::getGraphqlFieldsFromAnnotations($namespace, $methodsAnnotations, false, true);
231
232 1
        if (empty($fields)) {
233
            return [];
234
        }
235
236 1
        $interfaceConfiguration['fields'] = $fields;
237 1
        $interfaceConfiguration += self::getDescriptionConfiguration($classAnnotations);
238
239 1
        return ['type' => 'interface', 'config' => $interfaceConfiguration];
240
    }
241
242
    /**
243
     * Create a GraphQL Input type configuration from annotations on properties.
244
     *
245
     * @param string              $shortClassName
0 ignored issues
show
Bug introduced by
There is no parameter named $shortClassName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
246
     * @param AnnotationInputType $inputAnnotation
247
     * @param array               $propertiesAnnotations
248
     * @param string              $namespace
249
     *
250
     * @return array
251
     */
252 1
    private static function getGraphqlInputType(AnnotationInputType $inputAnnotation, array $classAnnotations, array $propertiesAnnotations, string $namespace)
253
    {
254 1
        $inputConfiguration = [];
255 1
        $fields = self::getGraphqlFieldsFromAnnotations($namespace, $propertiesAnnotations, true);
256
257 1
        if (empty($fields)) {
258
            return [];
259
        }
260
261 1
        $inputConfiguration['fields'] = $fields;
262 1
        $inputConfiguration += self::getDescriptionConfiguration($classAnnotations);
263
264 1
        return ['type' => $inputAnnotation->isRelay ? 'relay-mutation-input' : 'input-object', 'config' => $inputConfiguration];
265
    }
266
267
    /**
268
     * Get a Graphql scalar configuration from given scalar annotation.
269
     *
270
     * @param string           $shortClassName
0 ignored issues
show
Documentation introduced by
There is no parameter named $shortClassName. Did you maybe mean $className?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
271
     * @param string           $className
272
     * @param AnnotationScalar $scalarAnnotation
273
     * @param array            $classAnnotations
274
     *
275
     * @return array
276
     */
277 2
    private static function getGraphqlScalar(string $className, AnnotationScalar $scalarAnnotation, array $classAnnotations)
278
    {
279 2
        $scalarConfiguration = [];
280
281 2
        if ($scalarAnnotation->scalarType) {
282 1
            $scalarConfiguration['scalarType'] = self::formatExpression($scalarAnnotation->scalarType);
283
        } else {
284
            $scalarConfiguration = [
285 1
                'serialize' => [$className, 'serialize'],
286 1
                'parseValue' => [$className, 'parseValue'],
287 1
                'parseLiteral' => [$className, 'parseLiteral'],
288
            ];
289
        }
290
291 2
        $scalarConfiguration += self::getDescriptionConfiguration($classAnnotations);
292
293 2
        return ['type' => 'custom-scalar', 'config' => $scalarConfiguration];
294
    }
295
296
    /**
297
     * Get a Graphql Enum configuration from given enum annotation.
298
     *
299
     * @param string         $shortClassName
0 ignored issues
show
Bug introduced by
There is no parameter named $shortClassName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
300
     * @param AnnotationEnum $enumAnnotation
301
     * @param array          $classAnnotations
302
     * @param array          $constants
303
     *
304
     * @return array
305
     */
306 1
    private static function getGraphqlEnum(AnnotationEnum $enumAnnotation, array $classAnnotations, array $constants)
307
    {
308 1
        $enumValues = $enumAnnotation->values ? $enumAnnotation->values : [];
309
310 1
        $values = [];
311
312 1
        foreach ($constants as $name => $value) {
313
            $valueAnnotation = \current(\array_filter($enumValues, function ($enumValueAnnotation) use ($name) {
314 1
                return $enumValueAnnotation->name == $name;
315 1
            }));
316 1
            $valueConfig = [];
317 1
            $valueConfig['value'] = $value;
318
319 1
            if ($valueAnnotation && $valueAnnotation->description) {
320 1
                $valueConfig['description'] = $valueAnnotation->description;
321
            }
322
323 1
            if ($valueAnnotation && $valueAnnotation->deprecationReason) {
324
                $valueConfig['deprecationReason'] = $valueAnnotation->deprecationReason;
325
            }
326
327 1
            $values[$name] = $valueConfig;
328
        }
329
330 1
        $enumConfiguration = ['values' => $values];
331 1
        $enumConfiguration += self::getDescriptionConfiguration($classAnnotations);
332
333 1
        return ['type' => 'enum', 'config' => $enumConfiguration];
334
    }
335
336
    /**
337
     * Get a Graphql Union configuration from given union annotation.
338
     *
339
     * @param string          $shortClassName
0 ignored issues
show
Bug introduced by
There is no parameter named $shortClassName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
340
     * @param AnnotationUnion $unionAnnotation
341
     * @param array           $classAnnotations
342
     *
343
     * @return array
344
     */
345 1
    private static function getGraphqlUnion(AnnotationUnion $unionAnnotation, array $classAnnotations): array
346
    {
347 1
        $unionConfiguration = ['types' => $unionAnnotation->types];
348 1
        $unionConfiguration += self::getDescriptionConfiguration($classAnnotations);
349
350 1
        return ['type' => 'union', 'config' => $unionConfiguration];
351
    }
352
353
    /**
354
     * Create Graphql fields configuration based on annotation.
355
     *
356
     * @param string $namespace
357
     * @param array  $annotations
358
     * @param bool   $isInput
359
     * @param bool   $isMethod
360
     *
361
     * @return array
362
     */
363 10
    private static function getGraphqlFieldsFromAnnotations(string $namespace, array $annotations, bool $isInput = false, bool $isMethod = false): array
364
    {
365 10
        $fields = [];
366 10
        foreach ($annotations as $target => $annotations) {
367 10
            $fieldAnnotation = self::getFirstAnnotationMatching($annotations, 'Overblog\GraphQLBundle\Annotation\Field');
368 10
            $accessAnnotation = self::getFirstAnnotationMatching($annotations, 'Overblog\GraphQLBundle\Annotation\Access');
369 10
            $publicAnnotation = self::getFirstAnnotationMatching($annotations, 'Overblog\GraphQLBundle\Annotation\IsPublic');
370
371 10
            if (!$fieldAnnotation) {
372
                if ($accessAnnotation || $publicAnnotation) {
373
                    throw new InvalidArgumentException(\sprintf('The annotations "@Access" and/or "@Visible" defined on "%s" are only usable in addition of annotation "@Field"', $target));
374
                }
375
                continue;
376
            }
377
378
            // Ignore field with resolver when the type is an Input
379 10
            if ($fieldAnnotation->resolve && $isInput) {
380
                continue;
381
            }
382
383 10
            $propertyName = $target;
384 10
            $fieldType = $fieldAnnotation->type;
385 10
            $fieldConfiguration = [];
386 10
            if ($fieldType) {
387 7
                $fieldConfiguration['type'] = $fieldType;
388
            }
389
390 10
            $fieldConfiguration += self::getDescriptionConfiguration($annotations, true);
391
392 10
            if (!$isInput) {
393 9
                $args = [];
394 9
                if ($fieldAnnotation->args) {
395 1
                    foreach ($fieldAnnotation->args as $annotationArg) {
396 1
                        $args[$annotationArg->name] = ['type' => $annotationArg->type] + ($annotationArg->description ? ['description' => $annotationArg->description] : []);
397
                    }
398
399 1
                    if (!empty($args)) {
400 1
                        $fieldConfiguration['args'] = $args;
401
                    }
402
403
                    $args = \array_map(function ($a) {
404 1
                        return \sprintf("args['%s']", $a);
405 1
                    }, \array_keys($args));
406
                }
407
408 9
                $propertyName = $fieldAnnotation->name ?: $propertyName;
409
410 9
                if ($fieldAnnotation->resolve) {
411 1
                    $fieldConfiguration['resolve'] = self::formatExpression($fieldAnnotation->resolve);
412
                } else {
413 9
                    if ($isMethod) {
414 2
                        $fieldConfiguration['resolve'] = self::formatExpression(\sprintf('value.%s(%s)', $target, \implode(', ', $args)));
415 8
                    } elseif ($fieldAnnotation->name) {
416
                        $fieldConfiguration['resolve'] = self::formatExpression(\sprintf('value.%s', $target));
417
                    }
418
                }
419
420 9
                if ($fieldAnnotation->argsBuilder) {
421 1
                    if (\is_string($fieldAnnotation->argsBuilder)) {
422 1
                        $fieldConfiguration['argsBuilder'] = $fieldAnnotation->argsBuilder;
423 1
                    } elseif (\is_array($fieldAnnotation->argsBuilder)) {
424 1
                        list($builder, $builderConfig) = $fieldAnnotation->argsBuilder;
425 1
                        $fieldConfiguration['argsBuilder'] = ['builder' => $builder, 'config' => $builderConfig];
426
                    } else {
427
                        throw new InvalidArgumentException(\sprintf('The attribute "argsBuilder" on GraphQL annotation "@Field" defined on "%s" must be a string or an array where first index is the builder name and the second is the config.', $target));
428
                    }
429
                }
430
431 9
                if ($fieldAnnotation->fieldBuilder) {
432 2
                    if (\is_string($fieldAnnotation->fieldBuilder)) {
433 2
                        $fieldConfiguration['builder'] = $fieldAnnotation->fieldBuilder;
434 2
                    } elseif (\is_array($fieldAnnotation->fieldBuilder)) {
435 2
                        list($builder, $builderConfig) = $fieldAnnotation->fieldBuilder;
436 2
                        $fieldConfiguration['builder'] = $builder;
437 2
                        $fieldConfiguration['builderConfig'] = $builderConfig ?: [];
438
                    } else {
439 2
                        throw new InvalidArgumentException(\sprintf('The attribute "argsBuilder" on GraphQL annotation "@Field" defined on "%s" must be a string or an array where first index is the builder name and the second is the config.', $target));
440
                    }
441
                } else {
442 7
                    if (!$fieldType) {
443 1
                        if ($isMethod) {
444
                            throw new InvalidArgumentException(\sprintf('The attribute "type" on GraphQL annotation "@Field" is missing on method "%s" and cannot be auto-guesses.', $target));
445
                        } else {
446
                            try {
447 1
                                $fieldConfiguration['type'] = self::guessType($namespace, $annotations);
448
                            } catch (\Exception $e) {
449
                                throw new InvalidArgumentException(\sprintf('The attribute "type" on "@Field" defined on "%s" cannot be auto-guessed : %s.', $target, $e->getMessage()));
450
                            }
451
                        }
452
                    }
453
                }
454
455 9
                if ($accessAnnotation) {
456 1
                    $fieldConfiguration['access'] = self::formatExpression($accessAnnotation->value);
457
                }
458
459 9
                if ($publicAnnotation) {
460 1
                    $fieldConfiguration['public'] = self::formatExpression($publicAnnotation->value);
461
                }
462
            }
463
464 10
            $fields[$propertyName] = $fieldConfiguration;
465
        }
466
467 10
        return $fields;
468
    }
469
470
    /**
471
     * Get the config for description & deprecation reason.
472
     *
473
     * @param array $annotations
474
     * @param bool  $withDeprecation
475
     *
476
     * @return array
477
     */
478 14
    private static function getDescriptionConfiguration(array $annotations, bool $withDeprecation = false)
479
    {
480 14
        $config = [];
481 14
        $descriptionAnnotation = self::getFirstAnnotationMatching($annotations, 'Overblog\GraphQLBundle\Annotation\Description');
482 14
        if ($descriptionAnnotation) {
483 6
            $config['description'] = $descriptionAnnotation->value;
484
        }
485
486 14
        if ($withDeprecation) {
487 10
            $deprecatedAnnotation = self::getFirstAnnotationMatching($annotations, 'Overblog\GraphQLBundle\Annotation\Deprecated');
488 10
            if ($deprecatedAnnotation) {
489 1
                $config['deprecationReason'] = $deprecatedAnnotation->value;
490
            }
491
        }
492
493 14
        return $config;
494
    }
495
496
    /**
497
     * Get the first annotation matching given class.
498
     *
499
     * @param array        $annotations
500
     * @param string|array $annotationClass
501
     *
502
     * @return mixed
503
     */
504 14
    private static function getFirstAnnotationMatching(array $annotations, $annotationClass)
505
    {
506 14
        if (\is_string($annotationClass)) {
507 14
            $annotationClass = [$annotationClass];
508
        }
509
510 14
        foreach ($annotations as $annotation) {
511 14
            foreach ($annotationClass as $class) {
512 14
                if ($annotation instanceof $class) {
513 14
                    return $annotation;
514
                }
515
            }
516
        }
517
518 11
        return false;
519
    }
520
521
    /**
522
     * Format an expression (ie. add "@=" if not set).
523
     *
524
     * @param string $expression
525
     *
526
     * @return string
527
     */
528 6
    private static function formatExpression(string $expression)
529
    {
530 6
        return '@=' === \substr($expression, 0, 2) ? $expression : \sprintf('@=%s', $expression);
531
    }
532
533
    /**
534
     * Suffix a name if it is not already.
535
     *
536
     * @param string $name
537
     * @param string $suffix
538
     *
539
     * @return string
540
     */
541 2
    private static function suffixName(string $name, string $suffix)
542
    {
543 2
        return \substr($name, \strlen($suffix)) === $suffix ? $name : \sprintf('%s%s', $name, $suffix);
544
    }
545
546
    /**
547
     * Try to guess a field type base on is annotations.
548
     *
549
     * @param string $namespace
550
     * @param array  $annotations
551
     *
552
     * @return string|false
553
     */
554 1
    private static function guessType(string $namespace, array $annotations)
555
    {
556 1
        $columnAnnotation = self::getFirstAnnotationMatching($annotations, 'Doctrine\ORM\Mapping\Column');
557 1
        if ($columnAnnotation) {
558 1
            $type = self::resolveTypeFromDoctrineType($columnAnnotation->type);
559 1
            $nullable = $columnAnnotation->nullable;
560 1
            if ($type) {
561 1
                return $nullable ? $type : \sprintf('%s!', $type);
562
            } else {
563
                throw new \Exception(\sprintf('Unable to auto-guess GraphQL type from Doctrine type "%s"', $columnAnnotation->type));
564
            }
565
        }
566
567
        $associationAnnotations = [
568 1
            'Doctrine\ORM\Mapping\OneToMany' => true,
569
            'Doctrine\ORM\Mapping\OneToOne' => false,
570
            'Doctrine\ORM\Mapping\ManyToMany' => true,
571
            'Doctrine\ORM\Mapping\ManyToOne' => false,
572
        ];
573
574 1
        $associationAnnotation = self::getFirstAnnotationMatching($annotations, \array_keys($associationAnnotations));
575 1
        if ($associationAnnotation) {
576 1
            $target = self::fullyQualifiedClassName($associationAnnotation->targetEntity, $namespace);
577 1
            $type = self::resolveTypeFromClass($target, 'type');
578
579 1
            if ($type) {
580 1
                $isMultiple = $associationAnnotations[\get_class($associationAnnotation)];
581 1
                if ($isMultiple) {
582 1
                    return \sprintf('[%s]!', $type);
583
                } else {
584 1
                    $isNullable = false;
585 1
                    $joinColumn = self::getFirstAnnotationMatching($annotations, 'Doctrine\ORM\Mapping\JoinColumn');
586 1
                    if ($joinColumn) {
587 1
                        $isNullable = $joinColumn->nullable;
588
                    }
589
590 1
                    return \sprintf('%s%s', $type, $isNullable ? '' : '!');
591
                }
592
            } else {
593
                throw new \Exception(\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));
594
            }
595
        }
596
597
        throw new InvalidArgumentException(\sprintf('No Doctrine ORM annotation found.'));
598
    }
599
600
    /**
601
     * Resolve a Graphql Type from a class name.
602
     *
603
     * @param string $className
604
     * @param string $wantedType
605
     *
606
     * @return string|false
607
     */
608 1
    private static function resolveTypeFromClass(string $className, string $wantedType = null)
609
    {
610 1
        foreach (self::$classesMap as $gqlType => $config) {
611 1
            if ($config['class'] === $className) {
612 1
                if (!$wantedType || ($wantedType && $wantedType === $config['type'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $wantedType of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
613 1
                    return $gqlType;
614
                }
615
            }
616
        }
617
618
        return false;
619
    }
620
621
    /**
622
     * Resolve a FQN from classname and namespace.
623
     *
624
     * @param string $className
625
     * @param string $namespace
626
     *
627
     * @return string
628
     */
629 1
    public static function fullyQualifiedClassName(string $className, string $namespace)
630
    {
631 1
        if (false === \strpos($className, '\\') && $namespace) {
632 1
            return $namespace.'\\'.$className;
633
        }
634
635
        return $className;
636
    }
637
638
    /**
639
     * Resolve a GraphqlType from a doctrine type.
640
     *
641
     * @param string $doctrineType
642
     *
643
     * @return string|false
644
     */
645 1
    private static function resolveTypeFromDoctrineType(string $doctrineType)
646
    {
647 1
        switch ($doctrineType) {
648 1
            case 'integer':
649 1
            case 'smallint':
650 1
            case 'bigint':
651 1
                return 'Int';
652
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
653 1
            case 'string':
654
            case 'text':
655 1
                return 'String';
656
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
657
            case 'bool':
658
            case 'boolean':
659
                return 'Boolean';
660
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
661
            case 'float':
662
            case 'decimal':
663
                return 'Float';
664
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
665
            default:
666
                return false;
667
        }
668
    }
669
}
670