Passed
Pull Request — master (#64)
by David
01:38
created

InputTypeUtils   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 21
dl 0
loc 55
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getInputTypeNameAndClassName() 0 8 2
A validateReturnType() 0 21 4
A __construct() 0 5 1
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers;
5
6
use phpDocumentor\Reflection\Fqsen;
7
use phpDocumentor\Reflection\Types\Object_;
8
use ReflectionMethod;
9
10
class InputTypeUtils
11
{
12
    /**
13
     * @var AnnotationReader
14
     */
15
    private $annotationReader;
16
    /**
17
     * @var NamingStrategyInterface
18
     */
19
    private $namingStrategy;
20
21
    public function __construct(AnnotationReader $annotationReader,
22
                                NamingStrategyInterface $namingStrategy)
23
    {
24
        $this->annotationReader = $annotationReader;
25
        $this->namingStrategy = $namingStrategy;
26
    }
27
28
    /**
29
     * Returns an array with 2 elements: [ $inputName, $className ]
30
     *
31
     * @param ReflectionMethod $method
32
     * @return string[]
33
     */
34
    public function getInputTypeNameAndClassName(ReflectionMethod $method): array
35
    {
36
        $fqsen = ltrim((string) $this->validateReturnType($method), '\\');
37
        $factory = $this->annotationReader->getFactoryAnnotation($method);
38
        if ($factory === null) {
39
            throw new \RuntimeException($method->getDeclaringClass()->getName().'::'.$method->getName().' has no @Factory annotation.');
40
        }
41
        return [$this->namingStrategy->getInputTypeName($fqsen, $factory), $fqsen];
42
    }
43
44
    private function validateReturnType(ReflectionMethod $refMethod): Fqsen
45
    {
46
        $returnType = $refMethod->getReturnType();
47
        if ($returnType === null) {
48
            throw MissingTypeHintException::missingReturnType($refMethod);
49
        }
50
51
        if ($returnType->allowsNull()) {
52
            throw MissingTypeHintException::nullableReturnType($refMethod);
53
        }
54
55
        $type = (string) $returnType;
56
57
        $typeResolver = new \phpDocumentor\Reflection\TypeResolver();
58
59
        $phpdocType = $typeResolver->resolve($type);
60
        if (!$phpdocType instanceof Object_) {
61
            throw MissingTypeHintException::invalidReturnType($refMethod);
62
        }
63
64
        return $phpdocType->getFqsen();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $phpdocType->getFqsen() could return the type null which is incompatible with the type-hinted return phpDocumentor\Reflection\Fqsen. Consider adding an additional type-check to rule them out.
Loading history...
65
    }
66
}
67