Completed
Pull Request — master (#1214)
by
unknown
11:19
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
namespace JMS\Serializer\Metadata\Driver;
4
5
class DocBlockTypeResolver
6
{
7
    /** resolve type hints from property */
8
    private const CLASS_PROPERTY_TYPE_HINT_REGEX = "#@var[\s]*([^\n\$\s]*)#";
9
    /** resolve single use statements */
10
    private const SINGLE_USE_STATEMENTS_REGEX = '/^[^\S\r\n]*use[\s]*([^;\n]*)[\s]*;$/m';
11
    /** resolve group use statements */
12
    private const GROUP_USE_STATEMENTS_REGEX = '/^[^\S\r\n]*use[[\s]*([^;\n]*)[\s]*{([a-zA-Z0-9\s\n\r,]*)};$/m';
13
    private const GLOBAL_NAMESPACE_PREFIX = "\\";
14
15
    public function getPropertyDocblockTypeHint(\ReflectionProperty $reflectionProperty): ?string
16
    {
17
        preg_match_all(self::CLASS_PROPERTY_TYPE_HINT_REGEX, $reflectionProperty->getDocComment(), $matchedDocBlockParameterTypes);
18
        $typeHint = trim($matchedDocBlockParameterTypes[1][0]);
19
20
        $unionTypeHint = [];
21
        foreach (explode("|", $typeHint) as $singleTypeHint) {
22
            if ($singleTypeHint !== "null") {
23
                $unionTypeHint[] = $singleTypeHint;
24
            }
25
        }
26
        $typeHint = implode("|", $unionTypeHint);
27
        if (count($unionTypeHint) > 1) {
28
            throw new \InvalidArgumentException("Can't use union type {$typeHint} for collection in {$reflectionProperty->getDeclaringClass()->getName()}:{$reflectionProperty->getName()}");
29
        }
30
31
        if (strpos($typeHint, "[]") === false) {
32
            throw new \InvalidArgumentException("Can't use incorrect type {$typeHint} for collection in {$reflectionProperty->getDeclaringClass()->getName()}:{$reflectionProperty->getName()}");
33
        }
34
35
        $typeHint = rtrim($typeHint, "[]");
36
        if (!$this->hasGlobalNamespacePrefix($typeHint) && !$this->isPrimitiveType($typeHint)) {
37
            $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

37
            /** @scrutinizer ignore-call */ 
38
            $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...
38
        }
39
40
        return "array<" . ltrim($typeHint, "\\") . ">";
41
    }
42
43
    private function expandClassNameUsingUseStatements(string $typeHint, \ReflectionClass $declaringClass): string
44
    {
45
        $expandedClassName = $declaringClass->getNamespaceName() . "\\" . $typeHint;
46
        if (class_exists($expandedClassName)) {
47
            return $expandedClassName;
48
        }
49
50
        $classContents = file_get_contents($declaringClass->getFileName());
51
        $foundUseStatements = $this->gatherGroupUseStatements($classContents);
52
        $foundUseStatements = array_merge($this->gatherSingleUseStatements($classContents), $foundUseStatements);
53
54
        foreach ($foundUseStatements as $statementClassName) {
55
            if ($alias = explode("as", $statementClassName)) {
56
                if (array_key_exists(1, $alias) && trim($alias[1]) === $typeHint) {
57
                    return trim($alias[0]);
58
                }
59
            }
60
61
            if ($this->endsWith($statementClassName, $typeHint)) {
62
                return $statementClassName;
63
            }
64
        }
65
66
        return $typeHint;
67
    }
68
69
    private function endsWith(string $statementClassToCheck, string $typeHintToSearchFor) : bool
70
    {
71
        $typeHintToSearchFor = "\\" . $typeHintToSearchFor;
72
        $length = strlen($typeHintToSearchFor);
73
        if ($length == 0) {
74
            return true;
75
        }
76
77
        return (substr($statementClassToCheck, -$length) === $typeHintToSearchFor);
78
    }
79
80
    private function isPrimitiveType(string $type) : bool
81
    {
82
        return in_array($type, ["int", "float", "bool", "string"]);
83
    }
84
85
    private function hasGlobalNamespacePrefix(string $typeHint): bool
86
    {
87
        return $typeHint[0] === self::GLOBAL_NAMESPACE_PREFIX;
88
    }
89
90
    private function gatherGroupUseStatements(string $classContents): array
91
    {
92
        $foundUseStatements = [];
93
        preg_match_all(self::GROUP_USE_STATEMENTS_REGEX, $classContents, $foundGroupUseStatements);
94
        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...
95
            foreach (explode(",", $foundGroupUseStatements[2][$useStatementIndex]) as $singleUseStatement) {
96
                $foundUseStatements[] = trim($foundGroupUseStatements[1][$useStatementIndex]) . trim($singleUseStatement);
97
            }
98
        }
99
100
        return $foundUseStatements;
101
    }
102
103
    private function gatherSingleUseStatements(string $classContents): array
104
    {
105
        $foundUseStatements = [];
106
        preg_match_all(self::SINGLE_USE_STATEMENTS_REGEX, $classContents, $foundSingleUseStatements);
107
        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...
108
            $foundUseStatements[] = trim($foundSingleUseStatements[1][$useStatementIndex]);
109
        }
110
111
        return $foundUseStatements;
112
    }
113
114
    private function getDeclaringClassOrTrait(\ReflectionProperty $reflectionProperty): \ReflectionClass
115
    {
116
        foreach ($reflectionProperty->getDeclaringClass()->getTraits() as $trait) {
117
            foreach ($trait->getProperties() as $traitProperty) {
118
                if ($traitProperty->getName() === $reflectionProperty->getName()) {
119
                    return $this->getDeclaringClassOrTrait($traitProperty);
120
                }
121
            }
122
        }
123
124
        return $reflectionProperty->getDeclaringClass();
125
    }
126
}