Completed
Pull Request — master (#1214)
by
unknown
10:52
created

getPropertyDocblockTypeHint()   B

Complexity

Conditions 7
Paths 15

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 21
c 2
b 0
f 0
nc 15
nop 1
dl 0
loc 33
rs 8.6506
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\$]*)#';
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 ('null' !== $singleTypeHint) {
25
                $unionTypeHint[] = $singleTypeHint;
26
            }
27
        }
28
        $typeHint = implode('|', $unionTypeHint);
29
        if (count($unionTypeHint) > 1) {
30
            throw new \InvalidArgumentException(sprintf("Can't use union type %s for collection in %s:%s", $typeHint, $reflectionProperty->getDeclaringClass()->getName(), $reflectionProperty->getName()));
31
        }
32
33
        if (false !== strpos($typeHint, 'array<')) {
34
            $resolvedTypes = [];
35
            preg_match_all("#array<(.*)>#", $typeHint, $genericTypesToResolve);
36
            $genericTypesToResolve = $genericTypesToResolve[1][0];
37
            foreach (explode(",", $genericTypesToResolve) as $genericTypeToResolve) {
38
                $resolvedTypes[] = $this->resolveType(trim($genericTypeToResolve), $reflectionProperty);
39
            }
40
41
            return "array<" . implode(",", $resolvedTypes) . ">";
42
        }elseif (false === strpos($typeHint, '[]')) {
43
            throw new \InvalidArgumentException(sprintf("Can't use incorrect type %s for collection in %s:%s", $typeHint, $reflectionProperty->getDeclaringClass()->getName(), $reflectionProperty->getName()));
44
        }
45
46
        $typeHint = rtrim($typeHint, '[]');
47
        $typeHint = $this->resolveType($typeHint, $reflectionProperty);
48
49
        return 'array<' . ltrim($typeHint, '\\') . '>';
50
    }
51
52
    private function expandClassNameUsingUseStatements(string $typeHint, \ReflectionClass $declaringClass, \ReflectionProperty $reflectionProperty): string
53
    {
54
        $expandedClassName = $declaringClass->getNamespaceName() . '\\' . $typeHint;
55
        if (class_exists($expandedClassName)) {
56
            return $expandedClassName;
57
        }
58
59
        $classContents = file_get_contents($declaringClass->getFileName());
60
        $foundUseStatements = $this->gatherGroupUseStatements($classContents);
61
        $foundUseStatements = array_merge($this->gatherSingleUseStatements($classContents), $foundUseStatements);
62
63
        foreach ($foundUseStatements as $statementClassName) {
64
            if ($alias = explode('as', $statementClassName)) {
65
                if (array_key_exists(1, $alias) && trim($alias[1]) === $typeHint) {
66
                    return trim($alias[0]);
67
                }
68
            }
69
70
            if ($this->endsWith($statementClassName, $typeHint)) {
71
                return $statementClassName;
72
            }
73
        }
74
75
        throw new \InvalidArgumentException(sprintf("Can't use incorrect type %s for collection in %s:%s", $typeHint, $declaringClass->getName(), $reflectionProperty->getName()));
76
    }
77
78
    private function endsWith(string $statementClassToCheck, string $typeHintToSearchFor): bool
79
    {
80
        $typeHintToSearchFor = '\\' . $typeHintToSearchFor;
81
82
        return substr($statementClassToCheck, -strlen($typeHintToSearchFor)) === $typeHintToSearchFor;
83
    }
84
85
    private function isPrimitiveType(string $type): bool
86
    {
87
        return in_array($type, ['int', 'float', 'bool', 'string']);
88
    }
89
90
    private function hasGlobalNamespacePrefix(string $typeHint): bool
91
    {
92
        return self::GLOBAL_NAMESPACE_PREFIX === $typeHint[0];
93
    }
94
95
    private function gatherGroupUseStatements(string $classContents): array
96
    {
97
        $foundUseStatements = [];
98
        preg_match_all(self::GROUP_USE_STATEMENTS_REGEX, $classContents, $foundGroupUseStatements);
99
        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...
100
            foreach (explode(',', $foundGroupUseStatements[2][$useStatementIndex]) as $singleUseStatement) {
101
                $foundUseStatements[] = trim($foundGroupUseStatements[1][$useStatementIndex]) . trim($singleUseStatement);
102
            }
103
        }
104
105
        return $foundUseStatements;
106
    }
107
108
    private function gatherSingleUseStatements(string $classContents): array
109
    {
110
        $foundUseStatements = [];
111
        preg_match_all(self::SINGLE_USE_STATEMENTS_REGEX, $classContents, $foundSingleUseStatements);
112
        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...
113
            $foundUseStatements[] = trim($foundSingleUseStatements[1][$useStatementIndex]);
114
        }
115
116
        return $foundUseStatements;
117
    }
118
119
    private function getDeclaringClassOrTrait(\ReflectionProperty $reflectionProperty): \ReflectionClass
120
    {
121
        foreach ($reflectionProperty->getDeclaringClass()->getTraits() as $trait) {
122
            foreach ($trait->getProperties() as $traitProperty) {
123
                if ($traitProperty->getName() === $reflectionProperty->getName()) {
124
                    return $this->getDeclaringClassOrTrait($traitProperty);
125
                }
126
            }
127
        }
128
129
        return $reflectionProperty->getDeclaringClass();
130
    }
131
132
    private function resolveType(string $typeHint, \ReflectionProperty $reflectionProperty): string
133
    {
134
        if (!$this->hasGlobalNamespacePrefix($typeHint) && !$this->isPrimitiveType($typeHint)) {
135
            $typeHint = $this->expandClassNameUsingUseStatements($typeHint, $this->getDeclaringClassOrTrait($reflectionProperty), $reflectionProperty);
136
        }
137
138
        return $typeHint;
139
    }
140
}
141