Completed
Push — master ( 483c4c...50a0b2 )
by Alexander
02:27
created

NodeExpressionResolver::fetchReflectionClass()   D

Complexity

Conditions 9
Paths 15

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 17.7468

Importance

Changes 0
Metric Value
dl 0
loc 35
c 0
b 0
f 0
ccs 11
cts 21
cp 0.5238
rs 4.909
cc 9
eloc 21
nc 15
nop 1
crap 17.7468
1
<?php
2
/**
3
 * Parser Reflection API
4
 *
5
 * @copyright Copyright 2015, Lisachenko Alexander <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace Go\ParserReflection\ValueResolver;
12
13
use Go\ParserReflection\ReflectionClass;
14
use Go\ParserReflection\ReflectionException;
15
use Go\ParserReflection\ReflectionFileNamespace;
16
use PhpParser\Node;
17
use PhpParser\Node\Expr;
18
use PhpParser\Node\Scalar;
19
use PhpParser\Node\Scalar\MagicConst;
20
21
/**
22
 * Tries to resolve expression into value
23
 */
24
class NodeExpressionResolver
25
{
26
27
    /**
28
     * List of exception for constant fetch
29
     *
30
     * @var array
31
     */
32
    private static $notConstants = [
33
        'true'  => true,
34
        'false' => true,
35
        'null'  => true,
36
    ];
37
38
    /**
39
     * Name of the constant (if present)
40
     *
41
     * @var null|string
42
     */
43
    private $constantName = null;
44
45
    /**
46
     * Current reflection context for parsing
47
     *
48
     * @var mixed
49
     */
50
    private $context;
51
52
    /**
53
     * Flag if expression is constant
54
     *
55
     * @var bool
56
     */
57
    private $isConstant = false;
58
59
    /**
60
     * Node resolving level, 1 = top-level
61
     *
62
     * @var int
63
     */
64
    private $nodeLevel = 0;
65
66
    /**
67
     * @var mixed Value of expression/constant
68
     */
69
    private $value;
70
71 40
    public function __construct($context)
72
    {
73 40
        $this->context = $context;
74 40
    }
75
76 12
    public function getConstantName()
77
    {
78 12
        return $this->constantName;
79
    }
80
81 26
    public function getValue()
82
    {
83 26
        return $this->value;
84
    }
85
86 12
    public function isConstant()
87
    {
88 12
        return $this->isConstant;
89
    }
90
91
    /**
92
     * {@inheritDoc}
93
     */
94 26
    public function process(Node $node)
95
    {
96 26
        $this->nodeLevel    = 0;
97 26
        $this->isConstant   = false;
98 26
        $this->constantName = null;
99 26
        $this->value        = $this->resolve($node);
100 26
    }
101
102
    /**
103
     * Resolves node into valid value
104
     *
105
     * @param Node $node
106
     *
107
     * @return mixed
108
     */
109 26
    protected function resolve(Node $node)
110
    {
111 26
        $value = null;
112
        try {
113 26
            ++$this->nodeLevel;
114
115 26
            $nodeType   = $node->getType();
116 26
            $methodName = 'resolve' . str_replace('_', '', $nodeType);
117 26
            if (method_exists($this, $methodName)) {
118 26
                $value = $this->$methodName($node);
119
            }
120 26
        } finally {
121 26
            --$this->nodeLevel;
122
        }
123
124 26
        return $value;
125
    }
126
127 6
    protected function resolveScalarDNumber(Scalar\DNumber $node)
128
    {
129 6
        return $node->value;
130
    }
131
132 16
    protected function resolveScalarLNumber(Scalar\LNumber $node)
133
    {
134 16
        return $node->value;
135
    }
136
137 11
    protected function resolveScalarString(Scalar\String_ $node)
138
    {
139 11
        return $node->value;
140
    }
141
142
    protected function resolveScalarMagicConstMethod()
143
    {
144
        if ($this->context instanceof \ReflectionMethod) {
145
            $fullName = $this->context->getDeclaringClass()->getName() . '::' . $this->context->getShortName();
0 ignored issues
show
introduced by
Consider using $this->context->class. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
146
147
            return $fullName;
148
        }
149
150
        return '';
151
    }
152
153
    protected function resolveScalarMagicConstFunction()
154
    {
155
        if ($this->context instanceof \ReflectionFunctionAbstract) {
156
            return $this->context->getName();
157
        }
158
159
        return '';
160
    }
161
162 10
    protected function resolveScalarMagicConstNamespace()
163
    {
164 10
        if (method_exists($this->context, 'getNamespaceName')) {
165 8
            return $this->context->getNamespaceName();
166
        }
167
168 2
        if ($this->context instanceof ReflectionFileNamespace) {
169 2
            return $this->context->getName();
170
        }
171
172
        return '';
173
    }
174
175 9
    protected function resolveScalarMagicConstClass()
176
    {
177 9
        if ($this->context instanceof \ReflectionClass) {
178 2
            return $this->context->getName();
0 ignored issues
show
Bug introduced by
Consider using $this->context->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
179
        }
180 7
        if (method_exists($this->context, 'getDeclaringClass')) {
181
            $declaringClass = $this->context->getDeclaringClass();
182
            if ($declaringClass instanceof \ReflectionClass) {
183
                return $declaringClass->getName();
0 ignored issues
show
Bug introduced by
Consider using $declaringClass->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
184
            }
185
        }
186
187 7
        return '';
188
    }
189
190 1
    protected function resolveScalarMagicConstDir()
191
    {
192 1
        if (method_exists($this->context, 'getFileName')) {
193 1
            return dirname($this->context->getFileName());
194
        }
195
196
        return '';
197
    }
198
199 3
    protected function resolveScalarMagicConstFile()
200
    {
201 3
        if (method_exists($this->context, 'getFileName')) {
202 3
            return $this->context->getFileName();
203
        }
204
205
        return '';
206
    }
207
208 3
    protected function resolveScalarMagicConstLine(MagicConst\Line $node)
209
    {
210 3
        return $node->hasAttribute('startLine') ? $node->getAttribute('startLine') : 0;
211
    }
212
213 1
    protected function resolveScalarMagicConstTrait()
214
    {
215 1
        if ($this->context instanceof \ReflectionClass && $this->context->isTrait()) {
216 1
            return $this->context->getName();
0 ignored issues
show
Bug introduced by
Consider using $this->context->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
217
        }
218
219
        return '';
220
    }
221
222 17
    protected function resolveExprConstFetch(Expr\ConstFetch $node)
223
    {
224 17
        $constantValue = null;
225 17
        $isResolved    = false;
226
227
        /** @var ReflectionFileNamespace|null $fileNamespace */
228 17
        $fileNamespace = null;
0 ignored issues
show
Unused Code introduced by
$fileNamespace 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...
229 17
        $isFQNConstant = $node->name instanceof Node\Name\FullyQualified;
230 17
        $constantName  = $node->name->toString();
231
232 17
        if (!$isFQNConstant) {
233 17
            if (method_exists($this->context, 'getFileName')) {
234 17
                $fileName      = $this->context->getFileName();
235 17
                $namespaceName = $this->context->getNamespaceName();
236 17
                $fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
237 17
                if ($fileNamespace->hasConstant($constantName)) {
238 10
                    $constantValue = $fileNamespace->getConstant($constantName);
239 10
                    $constantName  = $fileNamespace->getName() . '\\' . $constantName;
240 10
                    $isResolved    = true;
241
                }
242
            }
243
        }
244
245 17
        if (!$isResolved && defined($constantName)) {
246 15
            $constantValue = constant($constantName);
247
        }
248
249 17
        if ($this->nodeLevel === 1 && !isset(self::$notConstants[$constantName])) {
250 10
            $this->isConstant   = true;
251 10
            $this->constantName = $constantName;
252
        }
253
254 17
        return $constantValue;
255
    }
256
257 5
    protected function resolveExprClassConstFetch(Expr\ClassConstFetch $node)
258
    {
259 5
        $refClass     = $this->fetchReflectionClass($node->class);
0 ignored issues
show
Bug introduced by
It seems like $node->class can also be of type object<PhpParser\Node\Expr>; however, Go\ParserReflection\Valu...:fetchReflectionClass() does only seem to accept object<PhpParser\Node\Name>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
260 5
        $constantName = $node->name;
261
262
        // special handling of ::class constants
263 5
        if ('class' === $constantName) {
264 1
            return $refClass->getName();
265
        }
266
        
267 5
        $this->isConstant = true;
268 5
        $this->constantName = (string)$node->class . '::' . $constantName;
269
270 5
        return $refClass->getConstant($constantName);
271
    }
272
273 9
    protected function resolveExprArray(Expr\Array_ $node)
274
    {
275 9
        $result = [];
276 9
        foreach ($node->items as $itemIndex => $arrayItem) {
277 8
            $itemValue = $this->resolve($arrayItem->value);
278 8
            $itemKey   = isset($arrayItem->key) ? $this->resolve($arrayItem->key) : $itemIndex;
279 8
            $result[$itemKey] = $itemValue;
280
        }
281
282 9
        return $result;
283
    }
284
285
    /**
286
     * Utility method to fetch reflection class instance by name
287
     *
288
     * Supports:
289
     *   'self' keyword
290
     *   'parent' keyword
291
     *    not-FQN class names
292
     *
293
     * @param Node\Name $node Class name node
294
     *
295
     * @return bool|\ReflectionClass
296
     *
297
     * @throws ReflectionException
298
     */
299 5
    private function fetchReflectionClass(Node\Name $node)
300
    {
301 5
        $className  = $node->toString();
302 5
        $isFQNClass = $node instanceof Node\Name\FullyQualified;
303 5
        if ($isFQNClass) {
304 2
            return new ReflectionClass($className);
305
        }
306
307 5
        if ('self' === $className) {
308 5
            if ($this->context instanceof \ReflectionClass) {
309 5
                return $this->context;
310
            } elseif (method_exists($this->context, 'getDeclaringClass')) {
311
                return $this->context->getDeclaringClass();
312
            }
313
        }
314
315 1
        if ('parent' === $className) {
316 1
            if ($this->context instanceof \ReflectionClass) {
317 1
                return $this->context->getParentClass();
318
            } elseif (method_exists($this->context, 'getDeclaringClass')) {
319
                return $this->context->getDeclaringClass()->getParentClass();
320
            }
321
        }
322
323
        if (method_exists($this->context, 'getFileName')) {
324
            /** @var ReflectionFileNamespace|null $fileNamespace */
325
            $fileName      = $this->context->getFileName();
326
            $namespaceName = $this->context->getNamespaceName();
327
328
            $fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
329
            return $fileNamespace->getClass($className);
330
        }
331
332
        throw new ReflectionException("Can not resolve class $className");
333
    }
334
}
335