Completed
Push — master ( 50a0b2...b57357 )
by Alexander
02:06
created

resolveExprBinaryOpSmaller()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 16
            $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 1
    protected function resolveExprBinaryOpPlus(Expr\BinaryOp\Plus $node)
286
    {
287 1
        return $this->resolve($node->left) + $this->resolve($node->right);
288
    }
289
290 1
    protected function resolveExprBinaryOpMinus(Expr\BinaryOp\Minus $node)
291
    {
292 1
        return $this->resolve($node->left) - $this->resolve($node->right);
293
    }
294
295 1
    protected function resolveExprBinaryOpMul(Expr\BinaryOp\Mul $node)
296
    {
297 1
        return $this->resolve($node->left) * $this->resolve($node->right);
298
    }
299
300 1
    protected function resolveExprBinaryOpDiv(Expr\BinaryOp\Div $node)
301
    {
302 1
        return $this->resolve($node->left) / $this->resolve($node->right);
303
    }
304
305 1
    protected function resolveExprBinaryOpMod(Expr\BinaryOp\Mod $node)
306
    {
307 1
        return $this->resolve($node->left) % $this->resolve($node->right);
308
    }
309
310 1
    protected function resolveExprBooleanNot(Expr\BooleanNot $node)
311
    {
312 1
        return !$this->resolve($node->expr);
313
    }
314
315 1
    protected function resolveExprBitwiseNot(Expr\BitwiseNot $node)
316
    {
317 1
        return ~$this->resolve($node->expr);
318
    }
319
320 1
    protected function resolveExprBinaryOpBitwiseOr(Expr\BinaryOp\BitwiseOr $node)
321
    {
322 1
        return $this->resolve($node->left) | $this->resolve($node->right);
323
    }
324
325 1
    protected function resolveExprBinaryOpBitwiseAnd(Expr\BinaryOp\BitwiseAnd $node)
326
    {
327 1
        return $this->resolve($node->left) & $this->resolve($node->right);
328
    }
329
330 1
    protected function resolveExprBinaryOpBitwiseXor(Expr\BinaryOp\BitwiseXor $node)
331
    {
332 1
        return $this->resolve($node->left) ^ $this->resolve($node->right);
333
    }
334
335 1
    protected function resolveExprBinaryOpShiftLeft(Expr\BinaryOp\ShiftLeft $node)
336
    {
337 1
        return $this->resolve($node->left) << $this->resolve($node->right);
338
    }
339
340 1
    protected function resolveExprBinaryOpShiftRight(Expr\BinaryOp\ShiftRight $node)
341
    {
342 1
        return $this->resolve($node->left) >> $this->resolve($node->right);
343
    }
344
345 1
    protected function resolveExprBinaryOpConcat(Expr\BinaryOp\Concat $node)
346
    {
347 1
        return $this->resolve($node->left) . $this->resolve($node->right);
348
    }
349
350 1
    protected function resolveExprTernary(Expr\Ternary $node)
351
    {
352 1
        if (isset($node->if)) {
353
            // Full syntax $a ? $b : $c;
354
355
            return $this->resolve($node->cond) ? $this->resolve($node->if) : $this->resolve($node->else);
356
        } else {
357
            // Short syntax $a ?: $c;
358
359 1
            return $this->resolve($node->cond) ?: $this->resolve($node->else);
360
        }
361
    }
362
363 1
    protected function resolveExprBinaryOpSmallerOrEqual(Expr\BinaryOp\SmallerOrEqual $node)
364
    {
365 1
        return $this->resolve($node->left) <= $this->resolve($node->right);
366
    }
367
368 1
    protected function resolveExprBinaryOpGreaterOrEqual(Expr\BinaryOp\GreaterOrEqual $node)
369
    {
370 1
        return $this->resolve($node->left) >= $this->resolve($node->right);
371
    }
372
373 1
    protected function resolveExprBinaryOpEqual(Expr\BinaryOp\Equal $node)
374
    {
375 1
        return $this->resolve($node->left) == $this->resolve($node->right);
376
    }
377
378 1
    protected function resolveExprBinaryOpNotEqual(Expr\BinaryOp\NotEqual $node)
379
    {
380 1
        return $this->resolve($node->left) != $this->resolve($node->right);
381
    }
382
383 1
    protected function resolveExprBinaryOpSmaller(Expr\BinaryOp\Smaller $node)
384
    {
385 1
        return $this->resolve($node->left) < $this->resolve($node->right);
386
    }
387
388 1
    protected function resolveExprBinaryOpGreater(Expr\BinaryOp\Greater $node)
389
    {
390 1
        return $this->resolve($node->left) > $this->resolve($node->right);
391
    }
392
393 1
    protected function resolveExprBinaryOpIdentical(Expr\BinaryOp\Identical $node)
394
    {
395 1
        return $this->resolve($node->left) === $this->resolve($node->right);
396
    }
397
398 1
    protected function resolveExprBinaryOpNotIdentical(Expr\BinaryOp\NotIdentical $node)
399
    {
400 1
        return $this->resolve($node->left) !== $this->resolve($node->right);
401
    }
402
403 1
    protected function resolveExprBinaryOpBooleanAnd(Expr\BinaryOp\BooleanAnd $node)
404
    {
405 1
        return $this->resolve($node->left) && $this->resolve($node->right);
406
    }
407
408 1
    protected function resolveExprBinaryOpLogicalAnd(Expr\BinaryOp\LogicalAnd $node)
409
    {
410 1
        return $this->resolve($node->left) and $this->resolve($node->right);
411
    }
412
413 1
    protected function resolveExprBinaryOpBooleanOr(Expr\BinaryOp\BooleanOr $node)
414
    {
415 1
        return $this->resolve($node->left) || $this->resolve($node->right);
416
    }
417
418 1
    protected function resolveExprBinaryOpLogicalOr(Expr\BinaryOp\LogicalOr $node)
419
    {
420 1
        return $this->resolve($node->left) or $this->resolve($node->right);
421
    }
422
423 1
    protected function resolveExprBinaryOpLogicalXor(Expr\BinaryOp\LogicalXor $node)
424
    {
425 1
        return $this->resolve($node->left) xor $this->resolve($node->right);
426
    }
427
428
    /**
429
     * Utility method to fetch reflection class instance by name
430
     *
431
     * Supports:
432
     *   'self' keyword
433
     *   'parent' keyword
434
     *    not-FQN class names
435
     *
436
     * @param Node\Name $node Class name node
437
     *
438
     * @return bool|\ReflectionClass
439
     *
440
     * @throws ReflectionException
441
     */
442 5
    private function fetchReflectionClass(Node\Name $node)
443
    {
444 5
        $className  = $node->toString();
445 5
        $isFQNClass = $node instanceof Node\Name\FullyQualified;
446 5
        if ($isFQNClass) {
447 2
            return new ReflectionClass($className);
448
        }
449
450 5
        if ('self' === $className) {
451 5
            if ($this->context instanceof \ReflectionClass) {
452 5
                return $this->context;
453
            } elseif (method_exists($this->context, 'getDeclaringClass')) {
454
                return $this->context->getDeclaringClass();
455
            }
456
        }
457
458 1
        if ('parent' === $className) {
459 1
            if ($this->context instanceof \ReflectionClass) {
460 1
                return $this->context->getParentClass();
461
            } elseif (method_exists($this->context, 'getDeclaringClass')) {
462
                return $this->context->getDeclaringClass()->getParentClass();
463
            }
464
        }
465
466
        if (method_exists($this->context, 'getFileName')) {
467
            /** @var ReflectionFileNamespace|null $fileNamespace */
468
            $fileName      = $this->context->getFileName();
469
            $namespaceName = $this->context->getNamespaceName();
470
471
            $fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
472
            return $fileNamespace->getClass($className);
473
        }
474
475
        throw new ReflectionException("Can not resolve class $className");
476
    }
477
}
478