Completed
Pull Request — master (#1214)
by
unknown
19:25 queued 04:25
created

DocBlockTypeResolver   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 120
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 56
dl 0
loc 120
rs 10
c 1
b 0
f 0
wmc 27

8 Methods

Rating   Name   Duplication   Size   Complexity  
B getPropertyDocblockTypeHint() 0 26 7
A getDeclaringClassOrTrait() 0 11 4
A hasGlobalNamespacePrefix() 0 3 1
A gatherSingleUseStatements() 0 9 2
A gatherGroupUseStatements() 0 11 3
A isPrimitiveType() 0 3 1
B expandClassNameUsingUseStatements() 0 24 7
A endsWith() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace JMS\Serializer\Metadata\Driver;
6
7
class DocBlockTypeResolver
8
{
9
    /** resolve type hints from property */
10
    private const CLASS_PROPERTY_TYPE_HINT_REGEX = "#@var[\s]*([^\n\$\s]*)#";
11
    /** resolve single use statements */
12
    private const SINGLE_USE_STATEMENTS_REGEX = '/^[^\S\r\n]*use[\s]*([^;\n]*)[\s]*;$/m';
13
    /** resolve group use statements */
14
    private const GROUP_USE_STATEMENTS_REGEX = '/^[^\S\r\n]*use[[\s]*([^;\n]*)[\s]*{([a-zA-Z0-9\s\n\r,]*)};$/m';
15
    private const GLOBAL_NAMESPACE_PREFIX = "\\";
16
17
    public function getPropertyDocblockTypeHint(\ReflectionProperty $reflectionProperty): ?string
18
    {
19
        preg_match_all(self::CLASS_PROPERTY_TYPE_HINT_REGEX, $reflectionProperty->getDocComment(), $matchedDocBlockParameterTypes);
20
        $typeHint = trim($matchedDocBlockParameterTypes[1][0]);
21
22
        $unionTypeHint = [];
23
        foreach (explode("|", $typeHint) as $singleTypeHint) {
24
            if ($singleTypeHint !== "null") {
25
                $unionTypeHint[] = $singleTypeHint;
26
            }
27
        }
28
        $typeHint = implode("|", $unionTypeHint);
29
        if (count($unionTypeHint) > 1) {
30
            throw new \InvalidArgumentException("Can't use union type {$typeHint} for collection in {$reflectionProperty->getDeclaringClass()->getName()}:{$reflectionProperty->getName()}");
31
        }
32
33
        if (strpos($typeHint, "[]") === false) {
34
            throw new \InvalidArgumentException("Can't use incorrect type {$typeHint} for collection in {$reflectionProperty->getDeclaringClass()->getName()}:{$reflectionProperty->getName()}");
35
        }
36
37
        $typeHint = rtrim($typeHint, "[]");
38
        if (!$this->hasGlobalNamespacePrefix($typeHint) && !$this->isPrimitiveType($typeHint)) {
39
            $typeHint = $this->expandClassNameUsingUseStatements($typeHint, $this->getDeclaringClassOrTrait($reflectionProperty), $reflectionProperty);
0 ignored issues
show
Unused Code introduced by
The call to JMS\Serializer\Metadata\...ameUsingUseStatements() has too many arguments starting with $reflectionProperty. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

39
            /** @scrutinizer ignore-call */ 
40
            $typeHint = $this->expandClassNameUsingUseStatements($typeHint, $this->getDeclaringClassOrTrait($reflectionProperty), $reflectionProperty);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
40
        }
41
42
        return "array<" . ltrim($typeHint, "\\") . ">";
43
    }
44
45
    private function expandClassNameUsingUseStatements(string $typeHint, \ReflectionClass $declaringClass): string
46
    {
47
        $expandedClassName = $declaringClass->getNamespaceName() . "\\" . $typeHint;
48
        if (class_exists($expandedClassName)) {
49
            return $expandedClassName;
50
        }
51
52
        $classContents = file_get_contents($declaringClass->getFileName());
53
        $foundUseStatements = $this->gatherGroupUseStatements($classContents);
54
        $foundUseStatements = array_merge($this->gatherSingleUseStatements($classContents), $foundUseStatements);
55
56
        foreach ($foundUseStatements as $statementClassName) {
57
            if ($alias = explode("as", $statementClassName)) {
58
                if (array_key_exists(1, $alias) && trim($alias[1]) === $typeHint) {
59
                    return trim($alias[0]);
60
                }
61
            }
62
63
            if ($this->endsWith($statementClassName, $typeHint)) {
64
                return $statementClassName;
65
            }
66
        }
67
68
        return $typeHint;
69
    }
70
71
    private function endsWith(string $statementClassToCheck, string $typeHintToSearchFor) : bool
72
    {
73
        $typeHintToSearchFor = "\\" . $typeHintToSearchFor;
74
        $length = strlen($typeHintToSearchFor);
75
        if ($length == 0) {
76
            return true;
77
        }
78
79
        return (substr($statementClassToCheck, -$length) === $typeHintToSearchFor);
80
    }
81
82
    private function isPrimitiveType(string $type) : bool
83
    {
84
        return in_array($type, ["int", "float", "bool", "string"]);
85
    }
86
87
    private function hasGlobalNamespacePrefix(string $typeHint): bool
88
    {
89
        return $typeHint[0] === self::GLOBAL_NAMESPACE_PREFIX;
90
    }
91
92
    private function gatherGroupUseStatements(string $classContents): array
93
    {
94
        $foundUseStatements = [];
95
        preg_match_all(self::GROUP_USE_STATEMENTS_REGEX, $classContents, $foundGroupUseStatements);
96
        for ($useStatementIndex = 0; $useStatementIndex < count($foundGroupUseStatements[0]); $useStatementIndex++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
97
            foreach (explode(",", $foundGroupUseStatements[2][$useStatementIndex]) as $singleUseStatement) {
98
                $foundUseStatements[] = trim($foundGroupUseStatements[1][$useStatementIndex]) . trim($singleUseStatement);
99
            }
100
        }
101
102
        return $foundUseStatements;
103
    }
104
105
    private function gatherSingleUseStatements(string $classContents): array
106
    {
107
        $foundUseStatements = [];
108
        preg_match_all(self::SINGLE_USE_STATEMENTS_REGEX, $classContents, $foundSingleUseStatements);
109
        for ($useStatementIndex = 0; $useStatementIndex < count($foundSingleUseStatements[0]); $useStatementIndex++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
110
            $foundUseStatements[] = trim($foundSingleUseStatements[1][$useStatementIndex]);
111
        }
112
113
        return $foundUseStatements;
114
    }
115
116
    private function getDeclaringClassOrTrait(\ReflectionProperty $reflectionProperty): \ReflectionClass
117
    {
118
        foreach ($reflectionProperty->getDeclaringClass()->getTraits() as $trait) {
119
            foreach ($trait->getProperties() as $traitProperty) {
120
                if ($traitProperty->getName() === $reflectionProperty->getName()) {
121
                    return $this->getDeclaringClassOrTrait($traitProperty);
122
                }
123
            }
124
        }
125
126
        return $reflectionProperty->getDeclaringClass();
127
    }
128
}
129