Test Failed
Pull Request — master (#6)
by David
02:17
created

ControllerQueryProvider::mapType()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 17
nc 10
nop 3
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\Boolean;
9
use phpDocumentor\Reflection\Types\Float_;
10
use phpDocumentor\Reflection\Types\Mixed;
11
use phpDocumentor\Reflection\Types\Object_;
12
use phpDocumentor\Reflection\Types\String_;
13
use Roave\BetterReflection\Reflection\ReflectionClass;
14
use Roave\BetterReflection\Reflection\ReflectionMethod;
15
use Doctrine\Common\Annotations\Reader;
16
use phpDocumentor\Reflection\Types\Integer;
17
use TheCodingMachine\GraphQL\Controllers\Annotations\Logged;
18
use TheCodingMachine\GraphQL\Controllers\Annotations\Mutation;
19
use TheCodingMachine\GraphQL\Controllers\Annotations\Query;
20
use TheCodingMachine\GraphQL\Controllers\Annotations\Right;
21
use TheCodingMachine\GraphQL\Controllers\Security\AuthenticationServiceInterface;
22
use TheCodingMachine\GraphQL\Controllers\Security\AuthorizationServiceInterface;
23
use Youshido\GraphQL\Field\Field;
24
use Youshido\GraphQL\Type\ListType\ListType;
25
use Youshido\GraphQL\Type\NonNullType;
26
use Youshido\GraphQL\Type\Scalar\BooleanType;
27
use Youshido\GraphQL\Type\Scalar\DateTimeType;
28
use Youshido\GraphQL\Type\Scalar\FloatType;
29
use Youshido\GraphQL\Type\Scalar\IntType;
30
use Youshido\GraphQL\Type\Scalar\StringType;
31
use Youshido\GraphQL\Type\TypeInterface;
32
use Youshido\GraphQL\Type\Union\UnionType;
33
34
/**
35
 * A query provider that looks for queries in a "controller"
36
 */
37
class ControllerQueryProvider implements QueryProviderInterface
38
{
39
    /**
40
     * @var object
41
     */
42
    private $controller;
43
    /**
44
     * @var Reader
45
     */
46
    private $annotationReader;
47
    /**
48
     * @var TypeMapperInterface
49
     */
50
    private $typeMapper;
51
    /**
52
     * @var HydratorInterface
53
     */
54
    private $hydrator;
55
    /**
56
     * @var AuthenticationServiceInterface
57
     */
58
    private $authenticationService;
59
    /**
60
     * @var AuthorizationServiceInterface
61
     */
62
    private $authorizationService;
63
64
    /**
65
     * @param object $controller
66
     */
67
    public function __construct($controller, Reader $annotationReader, TypeMapperInterface $typeMapper, HydratorInterface $hydrator, AuthenticationServiceInterface $authenticationService, AuthorizationServiceInterface $authorizationService)
68
    {
69
        $this->controller = $controller;
70
        $this->annotationReader = $annotationReader;
71
        $this->typeMapper = $typeMapper;
72
        $this->hydrator = $hydrator;
73
        $this->authenticationService = $authenticationService;
74
        $this->authorizationService = $authorizationService;
75
    }
76
77
    /**
78
     * @return Field[]
79
     */
80
    public function getQueries(): array
81
    {
82
        return $this->getFieldsByAnnotations(Query::class);
83
    }
84
85
    /**
86
     * @return Field[]
87
     */
88
    public function getMutations(): array
89
    {
90
        return $this->getFieldsByAnnotations(Mutation::class);
91
    }
92
93
    /**
94
     * @return Field[]
95
     */
96
    private function getFieldsByAnnotations(string $annotationName): array
97
    {
98
        $refClass = ReflectionClass::createFromInstance($this->controller);
99
100
        $queryList = [];
101
102
        $typeResolver = new \phpDocumentor\Reflection\TypeResolver();
103
104
        foreach ($refClass->getMethods() as $refMethod) {
105
            $standardPhpMethod = new \ReflectionMethod(get_class($this->controller), $refMethod->getName());
106
            // First, let's check the "Query" annotation
107
            $queryAnnotation = $this->annotationReader->getMethodAnnotation($standardPhpMethod, $annotationName);
108
109
            if ($queryAnnotation !== null) {
110
                if (!$this->isAuthorized($standardPhpMethod)) {
111
                    continue;
112
                }
113
114
                $methodName = $refMethod->getName();
115
116
                $args = $this->mapParameters($refMethod, $standardPhpMethod);
117
118
                $phpdocType = $typeResolver->resolve((string) $refMethod->getReturnType());
119
120
                $type = $this->mapType($phpdocType, $refMethod->getDocBlockReturnTypes(), $standardPhpMethod->getReturnType()->allowsNull());
0 ignored issues
show
Bug introduced by
It seems like $phpdocType defined by $typeResolver->resolve((...ethod->getReturnType()) on line 118 can be null; however, TheCodingMachine\GraphQL...ueryProvider::mapType() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
121
122
                $queryList[] = new QueryField($methodName, $type, $args, [$this->controller, $methodName], $this->hydrator);
123
            }
124
        }
125
126
        return $queryList;
127
    }
128
129
    /**
130
     * Checks the @Logged and @Right annotations.
131
     *
132
     * @param \ReflectionMethod $reflectionMethod
133
     * @return bool
134
     */
135
    private function isAuthorized(\ReflectionMethod $reflectionMethod) : bool
136
    {
137
        $loggedAnnotation = $this->annotationReader->getMethodAnnotation($reflectionMethod, Logged::class);
138
139
        if ($loggedAnnotation !== null && !$this->authenticationService->isLogged()) {
140
            return false;
141
        }
142
143
        $rightAnnotation = $this->annotationReader->getMethodAnnotation($reflectionMethod, Right::class);
144
        /** @var $rightAnnotation Right */
145
146
        if ($rightAnnotation !== null && !$this->authorizationService->isAllowed($rightAnnotation->getName())) {
147
            return false;
148
        }
149
150
        return true;
151
    }
152
153
    /**
154
     * Note: there is a bug in $refMethod->allowsNull that forces us to use $standardRefMethod->allowsNull instead.
155
     *
156
     * @param ReflectionMethod $refMethod
157
     * @param \ReflectionMethod $standardRefMethod
158
     * @return array
159
     */
160
    private function mapParameters(ReflectionMethod $refMethod, \ReflectionMethod $standardRefMethod)
161
    {
162
        $args = [];
163
164
        $typeResolver = new \phpDocumentor\Reflection\TypeResolver();
165
166
        foreach ($standardRefMethod->getParameters() as $standardParameter) {
167
            $allowsNull = $standardParameter->allowsNull();
168
            $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...
169
170
            $phpdocType = $typeResolver->resolve((string) $parameter->getType());
171
172
            $args[$parameter->getName()] = $this->mapType($phpdocType, $parameter->getDocBlockTypes(), $allowsNull);
0 ignored issues
show
Bug introduced by
It seems like $phpdocType defined by $typeResolver->resolve((... $parameter->getType()) on line 170 can be null; however, TheCodingMachine\GraphQL...ueryProvider::mapType() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
173
        }
174
175
        return $args;
176
    }
177
178
    /**
179
     * @param Type $type
180
     * @param Type[] $docBlockTypes
181
     * @return TypeInterface
182
     */
183
    private function mapType(Type $type, array $docBlockTypes, bool $isNullable): TypeInterface
184
    {
185
        $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...
186
187
        if ($type instanceof Array_ || $type instanceof Mixed) {
188
            if (!$isNullable) {
189
                // Let's check a "null" value in the docblock
190
                $isNullable = $this->isNullable($docBlockTypes);
191
            }
192
            $filteredDocBlockTypes = $this->typesWithoutNullable($docBlockTypes);
193
            if (empty($filteredDocBlockTypes)) {
194
                // TODO: improve error message
195
                throw new GraphQLException("Don't know how to handle type ".((string) $type));
196
            } elseif (count($filteredDocBlockTypes) === 1) {
197
                $graphQlType = $this->toGraphQlType($filteredDocBlockTypes[0]);
198
            } else {
199
                throw new GraphQLException('Union types are not supported (yet)');
200
                //$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...
201
                //$$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...
202
            }
203
        } else {
204
            $graphQlType = $this->toGraphQlType($type);
205
        }
206
207
        if (!$isNullable) {
208
            $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...
209
        }
210
211
        return $graphQlType;
212
    }
213
214
    /**
215
     * Casts a Type to a GraphQL type.
216
     * Does not deal with nullable.
217
     *
218
     * @param Type $type
219
     * @return TypeInterface
220
     */
221
    private function toGraphQlType(Type $type): TypeInterface
222
    {
223
        if ($type instanceof Integer) {
224
            return new IntType();
225
        } elseif ($type instanceof String_) {
226
            return new StringType();
227
        } elseif ($type instanceof Boolean) {
228
            return new BooleanType();
229
        } elseif ($type instanceof Float_) {
230
            return new FloatType();
231
        } elseif ($type instanceof Object_) {
232
            $fqcn = (string) $type->getFqsen();
233
            if ($fqcn === '\\DateTimeImmutable' || $fqcn === '\\DateTimeInterface') {
234
                return new DateTimeType();
235
            } elseif ($fqcn === '\\DateTime') {
236
                throw new GraphQLException('Type-hinting a parameter against DateTime is not allowed. Please use the DateTimeImmutable type instead.');
237
            }
238
239
            return $this->typeMapper->mapClassToType(ltrim($type->getFqsen(), '\\'));
240
        } elseif ($type instanceof Array_) {
241
            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...
242
        } else {
243
            throw new GraphQLException("Don't know how to handle type ".((string) $type));
244
        }
245
    }
246
247
    /**
248
     * Removes "null" from the list of types.
249
     *
250
     * @param Type[] $docBlockTypeHints
251
     * @return array
252
     */
253
    private function typesWithoutNullable(array $docBlockTypeHints): array
254
    {
255
        return array_filter($docBlockTypeHints, function ($item) {
256
            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...
257
        });
258
    }
259
260
    /**
261
     * @param Type[] $docBlockTypeHints
262
     * @return bool
263
     */
264
    private function isNullable(array $docBlockTypeHints): bool
265
    {
266
        foreach ($docBlockTypeHints as $docBlockTypeHint) {
267
            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...
268
                return true;
269
            }
270
        }
271
        return false;
272
    }
273
}
274