Passed
Push — master ( ba1e45...7b307a )
by David
03:05
created

ControllerQueryProvider::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 4
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers;
5
6
use phpDocumentor\Reflection\Type;
7
use phpDocumentor\Reflection\Types\Array_;
8
use phpDocumentor\Reflection\Types\Mixed;
9
use phpDocumentor\Reflection\Types\Object_;
10
use phpDocumentor\Reflection\Types\String_;
11
use Roave\BetterReflection\Reflection\ReflectionClass;
12
use Roave\BetterReflection\Reflection\ReflectionMethod;
13
use Doctrine\Common\Annotations\Reader;
14
use phpDocumentor\Reflection\Types\Integer;
15
use TheCodingMachine\GraphQL\Controllers\Annotations\Mutation;
16
use TheCodingMachine\GraphQL\Controllers\Annotations\Query;
17
use Youshido\GraphQL\Field\Field;
18
use Youshido\GraphQL\Type\ListType\ListType;
19
use Youshido\GraphQL\Type\NonNullType;
20
use Youshido\GraphQL\Type\Scalar\IntType;
21
use Youshido\GraphQL\Type\Scalar\StringType;
22
use Youshido\GraphQL\Type\TypeInterface;
23
use Youshido\GraphQL\Type\Union\UnionType;
24
25
/**
26
 * A query provider that looks for queries in a "controller"
27
 */
28
class ControllerQueryProvider implements QueryProviderInterface
29
{
30
    /**
31
     * @var object
32
     */
33
    private $controller;
34
    /**
35
     * @var Reader
36
     */
37
    private $annotationReader;
38
    /**
39
     * @var TypeMapperInterface
40
     */
41
    private $typeMapper;
42
    /**
43
     * @var HydratorInterface
44
     */
45
    private $hydrator;
46
47
    /**
48
     * @param object $controller
49
     */
50
    public function __construct($controller, Reader $annotationReader, TypeMapperInterface $typeMapper, HydratorInterface $hydrator)
51
    {
52
        $this->controller = $controller;
53
        $this->annotationReader = $annotationReader;
54
        $this->typeMapper = $typeMapper;
55
        $this->hydrator = $hydrator;
56
    }
57
58
    /**
59
     * @return Field[]
60
     */
61
    public function getQueries(): array
62
    {
63
        return $this->getFieldsByAnnotations(Query::class);
64
    }
65
66
    /**
67
     * @return Field[]
68
     */
69
    public function getMutations(): array
70
    {
71
        return $this->getFieldsByAnnotations(Mutation::class);
72
    }
73
74
    /**
75
     * @return Field[]
76
     */
77
    private function getFieldsByAnnotations(string $annotationName): array
78
    {
79
        $refClass = ReflectionClass::createFromInstance($this->controller);
80
81
        $queryList = [];
82
83
        foreach ($refClass->getMethods() as $refMethod) {
84
            $standardPhpMethod = new \ReflectionMethod(get_class($this->controller), $refMethod->getName());
85
            // First, let's check the "Query" annotation
86
            $queryAnnotation = $this->annotationReader->getMethodAnnotation($standardPhpMethod, $annotationName);
87
            if ($queryAnnotation !== null) {
88
                $methodName = $refMethod->getName();
89
90
                $args = $this->mapParameters($refMethod, $standardPhpMethod);
91
92
                $type = $this->mapType($refMethod->getReturnType()->getTypeObject(), $refMethod->getDocBlockReturnTypes(), $standardPhpMethod->getReturnType()->allowsNull());
93
94
                $queryList[] = new QueryField($methodName, $type, $args, [$this->controller, $methodName], $this->hydrator);
95
            }
96
        }
97
98
        return $queryList;
99
    }
100
101
    /**
102
     * Note: there is a bug in $refMethod->allowsNull that forces us to use $standardRefMethod->allowsNull instead.
103
     *
104
     * @param ReflectionMethod $refMethod
105
     * @param \ReflectionMethod $standardRefMethod
106
     * @return array
107
     */
108
    private function mapParameters(ReflectionMethod $refMethod, \ReflectionMethod $standardRefMethod)
109
    {
110
        $args = [];
111
        foreach ($standardRefMethod->getParameters() as $standardParameter) {
112
            $allowsNull = $standardParameter->allowsNull();
113
            $parameter = $refMethod->getParameter($standardParameter->getName());
0 ignored issues
show
Bug introduced by
Consider using $standardParameter->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
114
            $args[$parameter->getName()] = $this->mapType($parameter->getTypeHint(), $parameter->getDocBlockTypes(), $allowsNull);
115
        }
116
117
        return $args;
118
    }
119
120
    /**
121
     * @param Type $type
122
     * @param Type[] $docBlockTypes
123
     * @return TypeInterface
124
     */
125
    private function mapType(Type $type, array $docBlockTypes, bool $isNullable): TypeInterface
126
    {
127
        $graphQlType = null;
0 ignored issues
show
Unused Code introduced by
$graphQlType is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
128
129
        if ($type instanceof Array_ || $type instanceof Mixed) {
130
            if (!$isNullable) {
131
                // Let's check a "null" value in the docblock
132
                $isNullable = $this->isNullable($docBlockTypes);
133
            }
134
            $filteredDocBlockTypes = $this->typesWithoutNullable($docBlockTypes);
135
            if (empty($filteredDocBlockTypes)) {
136
                // TODO: improve error message
137
                throw new GraphQLException("Don't know how to handle type ".((string) $type));
138
            } elseif (count($filteredDocBlockTypes) === 1) {
139
                $graphQlType = $this->toGraphQlType($filteredDocBlockTypes[0]);
140
            } else {
141
                throw new GraphQLException('Union types are not supported (yet)');
142
                //$graphQlTypes = array_map([$this, 'toGraphQlType'], $filteredDocBlockTypes);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
143
                //$$graphQlType = new UnionType($graphQlTypes);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
144
            }
145
        } else {
146
            $graphQlType = $this->toGraphQlType($type);
147
        }
148
149
        if (!$isNullable) {
150
            $graphQlType = new NonNullType($graphQlType);
0 ignored issues
show
Documentation introduced by
$graphQlType is of type object<Youshido\GraphQL\Type\TypeInterface>, but the function expects a object<Youshido\GraphQL\Type\AbstractType>|string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
151
        }
152
153
        return $graphQlType;
154
    }
155
156
    /**
157
     * Casts a Type to a GraphQL type.
158
     * Does not deal with nullable.
159
     *
160
     * @param Type $type
161
     * @return TypeInterface
162
     */
163
    private function toGraphQlType(Type $type): TypeInterface
164
    {
165
        if ($type instanceof Integer) {
166
            return new IntType();
167
        } elseif ($type instanceof String_) {
168
            return new StringType();
169
        } elseif ($type instanceof Object_) {
170
            return $this->typeMapper->mapClassToType(ltrim($type->getFqsen(), '\\'));
171
        } elseif ($type instanceof Array_) {
172
            return new ListType(new NonNullType($this->toGraphQlType($type->getValueType())));
0 ignored issues
show
Documentation introduced by
$this->toGraphQlType($type->getValueType()) is of type object<Youshido\GraphQL\Type\TypeInterface>, but the function expects a object<Youshido\GraphQL\Type\AbstractType>|string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
173
        } else {
174
            throw new GraphQLException("Don't know how to handle type ".((string) $type));
175
        }
176
    }
177
178
    /**
179
     * Removes "null" from the list of types.
180
     *
181
     * @param Type[] $docBlockTypeHints
182
     * @return array
183
     */
184
    private function typesWithoutNullable(array $docBlockTypeHints): array
185
    {
186
        return array_filter($docBlockTypeHints, function($item) {
187
            return !$item instanceof Null_;
0 ignored issues
show
Bug introduced by
The class TheCodingMachine\GraphQL\Controllers\Null_ does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
188
        });
189
    }
190
191
    /**
192
     * @param Type[] $docBlockTypeHints
193
     * @return bool
194
     */
195
    private function isNullable(array $docBlockTypeHints): bool
196
    {
197
        foreach ($docBlockTypeHints as $docBlockTypeHint) {
198
            if ($docBlockTypeHint instanceof Null_) {
0 ignored issues
show
Bug introduced by
The class TheCodingMachine\GraphQL\Controllers\Null_ does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
199
                return true;
200
            }
201
        }
202
        return false;
203
    }
204
}
205