Completed
Push — master ( 332d1c...ed593a )
by Дмитрий
02:34
created

Expression   F

Complexity

Total Complexity 137

Size/Duplication

Total Lines 661
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 54

Test Coverage

Coverage 29.16%

Importance

Changes 24
Bugs 0 Features 7
Metric Value
wmc 137
c 24
b 0
f 7
lcom 1
cbo 54
dl 0
loc 661
ccs 114
cts 391
cp 0.2916
rs 1.1452

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
D factory() 0 96 33
C compile() 0 76 25
A passProperty() 0 4 1
A declareVariable() 0 13 2
B getNodeName() 0 21 7
A passCastBoolean() 0 16 4
B passCastInt() 0 17 5
B passCastFloat() 0 17 5
B passCastString() 0 17 5
A passCastUnset() 0 13 2
C passPropertyFetch() 0 39 7
B passConstFetch() 0 22 4
C passSymbol() 0 79 15
B passSymbolByRef() 0 46 6
A passExprVariable() 0 16 2
D getArray() 0 32 9
A constFetch() 0 21 4

How to fix   Complexity   

Complex Class

Complex classes like Expression often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Expression, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @author Patsura Dmitry https://github.com/ovr <[email protected]>
4
 */
5
6
namespace PHPSA\Compiler;
7
8
use InvalidArgumentException;
9
use PHPSA\Check;
10
use PHPSA\CompiledExpression;
11
use PHPSA\Context;
12
use PhpParser\Node;
13
use PHPSA\Definition\ClassDefinition;
14
use PHPSA\Exception\RuntimeException;
15
use PHPSA\Variable;
16
use PHPSA\Compiler\Expression\AbstractExpressionCompiler;
17
18
class Expression
0 ignored issues
show
Complexity introduced by
This class has a complexity of 137 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
19
{
20
    /**
21
     * @var Context
22
     */
23
    protected $context;
24
25
    /**
26
     * @param Context $context
27
     */
28 363
    public function __construct(Context $context)
29
    {
30 363
        $this->context = $context;
31 363
    }
32
33
    /**
34
     * @param $expr
35
     * @return ExpressionCompilerInterface|AbstractExpressionCompiler
36
     */
37 353
    protected function factory($expr)
38
    {
39 353
        switch (get_class($expr)) {
40
            /**
41
             * Call(s)
42
             */
43 353
            case 'PhpParser\Node\Expr\MethodCall':
44
                return new Expression\MethodCall();
45 353
            case 'PhpParser\Node\Expr\FuncCall':
46
                return new Expression\FunctionCall();
47 353
            case 'PhpParser\Node\Expr\StaticCall':
48
                return new Expression\StaticCall();
49
            /**
50
             * Operators
51
             */
52 353
            case 'PhpParser\Node\Expr\New_':
53
                return new Expression\Operators\NewOp();
54 353
            case 'PhpParser\Node\Expr\Instanceof_':
55
                return new Expression\Operators\InstanceOfOp();
56 353
            case 'PhpParser\Node\Expr\BinaryOp\Identical':
57 28
                return new Expression\BinaryOp\Identical();
58 325
            case 'PhpParser\Node\Expr\BinaryOp\Concat':
59
                return new Expression\Operators\Contact();
60 325
            case 'PhpParser\Node\Expr\BinaryOp\NotIdentical':
61 14
                return new Expression\BinaryOp\NotIdentical();
62 311
            case 'PhpParser\Node\Expr\BinaryOp\Equal':
63 34
                return new Expression\BinaryOp\Equal();
64 277
            case 'PhpParser\Node\Expr\BinaryOp\NotEqual':
65 17
                return new Expression\BinaryOp\NotEqual();
66
            /**
67
             * @link http://php.net/manual/en/language.operators.increment.php
68
             */
69 260
            case 'PhpParser\Node\Expr\PostInc':
70 4
                return new Expression\Operators\PostInc();
71 256
            case 'PhpParser\Node\Expr\PostDec':
72 4
                return new Expression\Operators\PostDec();
73
            /**
74
             * Arithmetical
75
             */
76 252
            case 'PhpParser\Node\Expr\BinaryOp\Div':
77 37
                return new Expression\Operators\Arithmetical\Div();
78 215
            case 'PhpParser\Node\Expr\BinaryOp\Plus':
79 41
                return new Expression\Operators\Arithmetical\Plus();
80 174
            case 'PhpParser\Node\Expr\BinaryOp\Minus':
81 18
                return new Expression\Operators\Arithmetical\Minus();
82 156
            case 'PhpParser\Node\Expr\BinaryOp\Mul':
83 35
                return new Expression\Operators\Arithmetical\Mul();
84 121
            case 'PhpParser\Node\Expr\BinaryOp\Mod':
85 35
                return new Expression\Operators\Arithmetical\Mod();
86
            /**
87
             * Bitwise
88
             * @link http://php.net/manual/ru/language.operators.bitwise.php
89
             */
90 86
            case 'PhpParser\Node\Expr\BinaryOp\BitwiseOr':
91
                return new Expression\Operators\Bitwise\BitwiseOr();
92 86
            case 'PhpParser\Node\Expr\BinaryOp\BitwiseXor':
93
                return new Expression\Operators\Bitwise\BitwiseXor();
94 86
            case 'PhpParser\Node\Expr\BinaryOp\BitwiseAnd':
95
                return new Expression\Operators\Bitwise\BitwiseAnd();
96 86
            case 'PhpParser\Node\Expr\BinaryOp\ShiftRight':
97
                return new Expression\Operators\Bitwise\ShiftRight();
98 86
            case 'PhpParser\Node\Expr\BinaryOp\ShiftLeft':
99
                return new Expression\Operators\Bitwise\ShiftLeft();
100 86
            case 'PhpParser\Node\Expr\BitwiseNot':
101
                return new Expression\Operators\Bitwise\BitwiseNot();
102
            /**
103
             * Logical
104
             */
105 86
            case 'PhpParser\Node\Expr\BinaryOp\BooleanOr':
106 10
                return new Expression\Operators\Logical\BooleanOr();
107 76
            case 'PhpParser\Node\Expr\BinaryOp\BooleanAnd':
108 5
                return new Expression\Operators\Logical\BooleanAnd();
109 71
            case 'PhpParser\Node\Expr\BooleanNot':
110 5
                return new Expression\Operators\Logical\BooleanNot();
111
            /**
112
             * Comparison
113
             */
114 66
            case 'PhpParser\Node\Expr\BinaryOp\Greater':
115 12
                return new Expression\Operators\Comparison\Greater();
116 54
            case 'PhpParser\Node\Expr\BinaryOp\GreaterOrEqual':
117 12
                return new Expression\Operators\Comparison\GreaterOrEqual();
118 42
            case 'PhpParser\Node\Expr\BinaryOp\Smaller':
119 12
                return new Expression\Operators\Comparison\Smaller();
120 30
            case 'PhpParser\Node\Expr\BinaryOp\SmallerOrEqual':
121 12
                return new Expression\Operators\Comparison\SmallerOrEqual();
122
            /**
123
             * Another
124
             */
125 18
            case 'PhpParser\Node\Expr\UnaryMinus':
126 9
                return new Expression\Operators\UnaryMinus();
127 9
            case 'PhpParser\Node\Expr\UnaryPlus':
128 9
                return new Expression\Operators\UnaryPlus();
129
        }
130
131
        return false;
132
    }
133
134
    /**
135
     * @param object|string $expr
136
     * @return CompiledExpression
137
     */
138 363
    public function compile($expr)
0 ignored issues
show
Complexity introduced by
This operation has 320 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

You can also find more information in the “Code” section of your repository.

Loading history...
139
    {
140 363
        if (is_string($expr)) {
141
            return new CompiledExpression(CompiledExpression::STRING, $expr);
142
        }
143
144 363
        if (!is_object($expr)) {
145
            throw new InvalidArgumentException('$expr must be string/object');
146
        }
147
148 363
        $className = get_class($expr);
149
        switch ($className) {
150 363
            case 'PhpParser\Node\Expr\PropertyFetch':
151
                return $this->passPropertyFetch($expr);
152 363
            case 'PhpParser\Node\Stmt\Property':
153
                return $this->passProperty($expr);
154 363
            case 'PhpParser\Node\Expr\ClassConstFetch':
155
                return $this->passConstFetch($expr);
156 363
            case 'PhpParser\Node\Expr\Assign':
157
                return $this->passSymbol($expr);
158 363
            case 'PhpParser\Node\Expr\AssignRef':
159
                return $this->passSymbolByRef($expr);
160 363
            case 'PhpParser\Node\Expr\Variable':
161
                return $this->passExprVariable($expr);
162
            /**
163
             * Cast operators
164
             */
165 363
            case 'PhpParser\Node\Expr\Cast\Bool_':
166
                return $this->passCastBoolean($expr);
167 363
            case 'PhpParser\Node\Expr\Cast\Int_':
168
                return $this->passCastInt($expr);
169 363
            case 'PhpParser\Node\Expr\Cast\Double':
170
                return $this->passCastFloat($expr);
171 363
            case 'PhpParser\Node\Expr\Cast\String_':
172
                return $this->passCastString($expr);
173 363
            case 'PhpParser\Node\Expr\Cast\Unset_':
174
                return $this->passCastUnset($expr);
175
            /**
176
             * Expressions
177
             */
178 363
            case 'PhpParser\Node\Expr\Array_':
179 11
                return $this->getArray($expr);
180 362
            case 'PhpParser\Node\Expr\ConstFetch':
181
                return $this->constFetch($expr);
182 362
            case 'PhpParser\Node\Name':
183
                return $this->getNodeName($expr);
184
            /**
185
             * Simple Scalar(s)
186
             */
187 362
            case 'PHPSA\Node\Scalar\Nil':
188 8
                return new CompiledExpression(CompiledExpression::NULL);
189 361
            case 'PhpParser\Node\Scalar\LNumber':
190 256
                return new CompiledExpression(CompiledExpression::INTEGER, $expr->value);
191 358
            case 'PhpParser\Node\Scalar\DNumber':
192 131
                return new CompiledExpression(CompiledExpression::DOUBLE, $expr->value);
193 357
            case 'PhpParser\Node\Scalar\String_':
194 8
                return new CompiledExpression(CompiledExpression::STRING, $expr->value);
195 355
            case 'PHPSA\Node\Scalar\Boolean':
196 60
                return new CompiledExpression(CompiledExpression::BOOLEAN, $expr->value);
197 353
            case 'PHPSA\Node\Scalar\Fake':
198 29
                return new CompiledExpression($expr->type, $expr->value);
199
        }
200
201 353
        $expressionCompiler = $this->factory($expr);
202 353
        if (!$expressionCompiler) {
203
            $this->context->debug("Expression compiler is not implemented for {$className}");
204
            return new CompiledExpression(CompiledExpression::UNIMPLEMENTED);
205
        }
206
207 353
        $result = $expressionCompiler->pass($expr, $this->context);
208 353
        if (!$result instanceof CompiledExpression) {
209
            throw new RuntimeException('Please return CompiledExpression from ' . get_class($expressionCompiler));
210
        }
211
212 353
        return $result;
213
    }
214
215
    /**
216
     * @todo Implement
217
     *
218
     * @param Node\Stmt\Property $st
219
     * @return CompiledExpression
220
     */
221
    public function passProperty(Node\Stmt\Property $st)
0 ignored issues
show
Unused Code introduced by
The parameter $st is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Comprehensibility introduced by
Avoid variables with short names like $st. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
222
    {
223
        return new CompiledExpression();
224
    }
225
226
    /**
227
     * @param Node\Expr\Variable $expr
228
     * @return CompiledExpression
229
     */
230
    public function declareVariable(Node\Expr\Variable $expr)
231
    {
232
        $variable = $this->context->getSymbol($expr->name);
233
        if ($variable) {
234
            $variable->incGets();
235
            return new CompiledExpression($variable->getType(), $variable->getValue(), $variable);
236
        }
237
238
        $symbol = new Variable($expr->name, null, CompiledExpression::UNKNOWN, $this->context->getCurrentBranch());
0 ignored issues
show
Bug introduced by
It seems like $expr->name can also be of type object<PhpParser\Node\Expr>; however, PHPSA\Variable::__construct() does only seem to accept string, 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...
239
        $this->context->addVariable($symbol);
240
241
        return new CompiledExpression;
242
    }
243
244
    /**
245
     * @param Node\Name $expr
246
     * @return CompiledExpression
247
     */
248
    public function getNodeName(Node\Name $expr)
249
    {
250
        if ($expr->parts[0] === 'null') {
251
            return new CompiledExpression(CompiledExpression::NULL);
252
        }
253
254
        if (in_array($expr, ['self', 'static'])) {
255
            $scopePointer = $this->context->scopePointer;
256
            if ($scopePointer) {
257
                if ($scopePointer->isClassMethod()) {
258
                    $classMethod = $scopePointer->getObject();
259
                    if ($classMethod && $classMethod->isStatic()) {
260
                        return CompiledExpression::fromZvalValue($this->context->scope);
261
                    }
262
                }
263
            }
264
        }
265
266
        $this->context->debug('[Unknown] How to get Node\Name for ' . $expr);
267
        return new CompiledExpression();
268
    }
269
270
    /**
271
     * (bool) {$expr}
272
     *
273
     * @param Node\Expr\Cast\Bool_ $expr
274
     * @return CompiledExpression
275
     */
276
    protected function passCastBoolean(Node\Expr\Cast\Bool_ $expr)
277
    {
278
        $expression = new Expression($this->context);
279
        $compiledExpression = $expression->compile($expr->expr);
280
281
        switch ($compiledExpression->getType()) {
282
            case CompiledExpression::BOOLEAN:
283
                $this->context->notice('stupid-cast', "You are trying to cast 'boolean' to 'boolean'", $expr);
284
                return $compiledExpression;
285
            case CompiledExpression::DOUBLE:
286
            case CompiledExpression::INTEGER:
287
                return new CompiledExpression(CompiledExpression::BOOLEAN, (bool) $compiledExpression->getValue());
288
        }
289
290
        return new CompiledExpression();
291
    }
292
293
    /**
294
     * (int) {$expr}
295
     *
296
     * @param Node\Expr\Cast\Int_ $expr
297
     * @return CompiledExpression
298
     */
299
    protected function passCastInt(Node\Expr\Cast\Int_ $expr)
300
    {
301
        $expression = new Expression($this->context);
302
        $compiledExpression = $expression->compile($expr->expr);
303
304
        switch ($compiledExpression->getType()) {
305
            case CompiledExpression::INTEGER:
306
                $this->context->notice('stupid-cast', "You are trying to cast 'int' to 'int'", $expr);
307
                return $compiledExpression;
308
            case CompiledExpression::BOOLEAN:
309
            case CompiledExpression::DOUBLE:
310
            case CompiledExpression::STRING:
311
                return new CompiledExpression(CompiledExpression::INTEGER, (int) $compiledExpression->getValue());
312
        }
313
314
        return new CompiledExpression();
315
    }
316
317
    /**
318
     * (float) {$expr}
319
     *
320
     * @param Node\Expr\Cast\Double $expr
321
     * @return CompiledExpression
322
     */
323
    protected function passCastFloat(Node\Expr\Cast\Double $expr)
324
    {
325
        $expression = new Expression($this->context);
326
        $compiledExpression = $expression->compile($expr->expr);
327
328
        switch ($compiledExpression->getType()) {
329
            case CompiledExpression::DOUBLE:
330
                $this->context->notice('stupid-cast', "You are trying to cast 'float' to 'float'", $expr);
331
                return $compiledExpression;
332
            case CompiledExpression::BOOLEAN:
333
            case CompiledExpression::INTEGER:
334
            case CompiledExpression::STRING:
335
                return new CompiledExpression(CompiledExpression::DOUBLE, (float) $compiledExpression->getValue());
336
        }
337
338
        return new CompiledExpression();
339
    }
340
341
    /**
342
     * (string) {$expr}
343
     *
344
     * @param Node\Expr\Cast\String_ $expr
345
     * @return CompiledExpression
346
     */
347
    protected function passCastString(Node\Expr\Cast\String_ $expr)
348
    {
349
        $expression = new Expression($this->context);
350
        $compiledExpression = $expression->compile($expr->expr);
351
352
        switch ($compiledExpression->getType()) {
353
            case CompiledExpression::STRING:
354
                $this->context->notice('stupid-cast', "You are trying to cast 'string' to 'string'", $expr);
355
                return $compiledExpression;
356
            case CompiledExpression::BOOLEAN:
357
            case CompiledExpression::INTEGER:
358
            case CompiledExpression::DOUBLE:
359
                return new CompiledExpression(CompiledExpression::DOUBLE, (string) $compiledExpression->getValue());
360
        }
361
362
        return new CompiledExpression();
363
    }
364
365
    /**
366
     * (unset) {$expr}
367
     *
368
     * @param Node\Expr\Cast\Unset_ $expr
369
     * @return CompiledExpression
370
     */
371
    protected function passCastUnset(Node\Expr\Cast\Unset_ $expr)
372
    {
373
        $expression = new Expression($this->context);
374
        $compiledExpression = $expression->compile($expr->expr);
375
376
        switch ($compiledExpression->getType()) {
377
            case CompiledExpression::NULL:
378
                $this->context->notice('stupid-cast', "You are trying to cast 'unset' to 'null'", $expr);
379
                return $compiledExpression;
380
        }
381
382
        return new CompiledExpression(CompiledExpression::NULL, null);
383
    }
384
385
    /**
386
     * @param Node\Expr\PropertyFetch $expr
387
     * @return CompiledExpression
388
     */
389
    protected function passPropertyFetch(Node\Expr\PropertyFetch $expr)
390
    {
391
        $propertNameCE = $this->compile($expr->name);
392
393
        $scopeExpression = $this->compile($expr->var);
394
        if ($scopeExpression->isObject()) {
395
            $scopeExpressionValue = $scopeExpression->getValue();
396
            if ($scopeExpressionValue instanceof ClassDefinition) {
397
                $propertyName = $propertNameCE->isString() ? $propertNameCE->getValue() : false;
398
                if ($propertyName) {
399
                    if ($scopeExpressionValue->hasProperty($propertyName, true)) {
400
                        $property = $scopeExpressionValue->getProperty($propertyName, true);
401
                        return $this->compile($property);
402
                    } else {
403
                        $this->context->notice(
404
                            'undefined-property',
405
                            sprintf(
406
                                'Property %s does not exist in %s scope',
407
                                $propertyName,
408
                                $scopeExpressionValue->getName()
409
                            ),
410
                            $expr
411
                        );
412
                    }
413
                }
414
            }
415
        } elseif (!$scopeExpression->canBeObject()) {
416
            return new CompiledExpression(CompiledExpression::UNKNOWN);
417
        }
418
419
        $this->context->notice(
420
            'property-fetch-on-non-object',
421
            "It's not possible to fetch property on not object",
422
            $expr,
423
            Check::CHECK_BETA
424
        );
425
426
        return new CompiledExpression(CompiledExpression::UNKNOWN);
427
    }
428
429
    /**
430
     * @param Node\Expr\ClassConstFetch $expr
431
     * @return CompiledExpression
432
     */
433
    protected function passConstFetch(Node\Expr\ClassConstFetch $expr)
434
    {
435
        $leftCE = $this->compile($expr->class);
436
        if ($leftCE->isObject()) {
437
            $leftCEValue = $leftCE->getValue();
438
            if ($leftCEValue instanceof ClassDefinition) {
439
                if (!$leftCEValue->hasConst($expr->name)) {
440
                    $this->context->notice(
441
                        'undefined-const',
442
                        sprintf('Constant %s does not exist in %s scope', $expr->name, $scope),
0 ignored issues
show
Bug introduced by
The variable $scope does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
443
                        $expr
444
                    );
445
                    return new CompiledExpression(CompiledExpression::UNKNOWN);
446
                }
447
448
                return new CompiledExpression();
449
            }
450
        }
451
452
        $this->context->debug('Unknown const fetch');
453
        return new CompiledExpression();
454
    }
455
456
    /**
457
     * @param Node\Expr\Assign $expr
458
     * @return CompiledExpression
459
     */
460
    protected function passSymbol(Node\Expr\Assign $expr)
461
    {
462
        $expression = new Expression($this->context);
463
        $compiledExpression = $expression->compile($expr->expr);
464
465
        if ($expr->var instanceof Node\Expr\List_) {
466
            $isCorrectType = false;
467
468
            switch ($compiledExpression->getType()) {
469
                case CompiledExpression::ARR:
470
                    $isCorrectType = true;
471
                    break;
472
            }
473
474
            if ($expr->var->vars) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $expr->var->vars of type PhpParser\Node\Expr[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
475
                foreach ($expr->var->vars as $key => $var) {
476
                    if ($var instanceof Node\Expr\Variable) {
477
                        $name = $expr->var->name;
0 ignored issues
show
Bug introduced by
The property name does not seem to exist in PhpParser\Node\Expr\List_.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
478
479
                        $symbol = $this->context->getSymbol($name);
480
                        if (!$symbol) {
481
                            $symbol = new Variable(
482
                                $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 477 can also be of type object<PhpParser\Node\Expr>; however, PHPSA\Variable::__construct() does only seem to accept string, 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...
483
                                null,
484
                                CompiledExpression::UNKNOWN,
485
                                $this->context->getCurrentBranch()
486
                            );
487
                            $this->context->addVariable($symbol);
488
                        }
489
490
                        if (!$isCorrectType) {
491
                            $symbol->modify(CompiledExpression::NULL, null);
492
                        }
493
494
                        $symbol->incSets();
495
                    }
496
                }
497
            }
498
499
            return new CompiledExpression();
500
        }
501
502
        if ($expr->var instanceof Node\Expr\Variable) {
503
            $name = $expr->var->name;
504
505
            $symbol = $this->context->getSymbol($name);
506
            if ($symbol) {
507
                $symbol->modify($compiledExpression->getType(), $compiledExpression->getValue());
508
            } else {
509
                $symbol = new Variable(
510
                    $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 503 can also be of type object<PhpParser\Node\Expr>; however, PHPSA\Variable::__construct() does only seem to accept string, 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...
511
                    $compiledExpression->getValue(),
512
                    $compiledExpression->getType(),
513
                    $this->context->getCurrentBranch()
514
                );
515
                $this->context->addVariable($symbol);
516
            }
517
518
            $symbol->incSets();
519
            return $compiledExpression;
520
        }
521
522
        if ($expr->var instanceof Node\Expr\PropertyFetch) {
523
            $compiledExpression = $this->compile($expr->var->var);
524
            if ($compiledExpression->getType() == CompiledExpression::OBJECT) {
525
                $objectDefinition = $compiledExpression->getValue();
526
                if ($objectDefinition instanceof ClassDefinition) {
527
                    if (is_string($expr->var->name)) {
528
                        if ($objectDefinition->hasProperty($expr->var->name)) {
529
                            return $this->compile($objectDefinition->getProperty($expr->var->name));
530
                        }
531
                    }
532
                }
533
            }
534
        }
535
536
        $this->context->debug('Unknown how to pass symbol');
537
        return new CompiledExpression();
538
    }
539
540
    /**
541
     * @param Node\Expr\AssignRef $expr
542
     * @return CompiledExpression
543
     */
544
    protected function passSymbolByRef(Node\Expr\AssignRef $expr)
545
    {
546
        if ($expr->var instanceof \PhpParser\Node\Expr\List_) {
547
            return new CompiledExpression();
548
        }
549
550
        if ($expr->var instanceof Node\Expr\Variable) {
551
            $name = $expr->var->name;
552
553
            $expression = new Expression($this->context);
554
            $compiledExpression = $expression->compile($expr->expr);
555
556
            $symbol = $this->context->getSymbol($name);
557
            if ($symbol) {
558
                $symbol->modify($compiledExpression->getType(), $compiledExpression->getValue());
559
560
                if ($expr->expr instanceof Node\Expr\Variable) {
561
                    $rightVarName = $expr->expr->name;
562
563
                    $rightSymbol = $this->context->getSymbol($rightVarName);
564
                    if ($rightSymbol) {
565
                        $rightSymbol->incUse();
566
                        $symbol->setReferencedTo($rightSymbol);
567
                    } else {
568
                        $this->context->debug('Cannot fetch variable by name: ' . $rightVarName);
569
                    }
570
                }
571
572
                $this->context->debug('Unknown how to pass referenced to symbol: ' . get_class($expr->expr));
573
            } else {
574
                $symbol = new Variable(
575
                    $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 551 can also be of type object<PhpParser\Node\Expr>; however, PHPSA\Variable::__construct() does only seem to accept string, 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...
576
                    $compiledExpression->getValue(),
577
                    $compiledExpression->getType(),
578
                    $this->context->getCurrentBranch()
579
                );
580
                $this->context->addVariable($symbol);
581
            }
582
583
            $symbol->incSets();
584
            return $compiledExpression;
585
        }
586
587
        $this->context->debug('Unknown how to pass symbol by ref');
588
        return new CompiledExpression();
589
    }
590
591
    /**
592
     * @param Node\Expr\Variable $expr
593
     * @return CompiledExpression
594
     */
595
    protected function passExprVariable(Node\Expr\Variable $expr)
596
    {
597
        $variable = $this->context->getSymbol($expr->name);
598
        if ($variable) {
599
            $variable->incGets();
600
            return new CompiledExpression($variable->getType(), $variable->getValue(), $variable);
601
        }
602
603
        $this->context->notice(
604
            'undefined-variable',
605
            sprintf('You trying to use undefined variable $%s', $expr->name),
606
            $expr
607
        );
608
609
        return new CompiledExpression();
610
    }
611
612
    /**
613
     * Compile Array_ expression to CompiledExpression
614
     *
615
     * @param Node\Expr\Array_ $expr
616
     * @return CompiledExpression
617
     */
618 11
    protected function getArray(Node\Expr\Array_ $expr)
619
    {
620 11
        if ($expr->items === array()) {
621 8
            return new CompiledExpression(CompiledExpression::ARR, array());
622
        }
623
624 3
        $resultArray = array();
625
626 3
        foreach ($expr->items as $item) {
627 3
            $compiledValueResult = $this->compile($item->value);
628 3
            if ($item->key) {
629 1
                $compiledKeyResult = $this->compile($item->key);
630 1
                switch ($compiledKeyResult->getType()) {
631 1
                    case CompiledExpression::INTEGER:
632 1
                    case CompiledExpression::DOUBLE:
633 1
                    case CompiledExpression::BOOLEAN:
634 1
                    case CompiledExpression::NULL:
635 1
                    case CompiledExpression::STRING:
636 1
                        $resultArray[$compiledKeyResult->getValue()] = $compiledValueResult->getValue();
637 1
                        break;
638
                    default:
639
                        $this->context->debug("Type {$compiledKeyResult->getType()} is not supported for key value");
640
                        return new CompiledExpression(CompiledExpression::ARR);
641
                        break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
642 1
                }
643 1
            } else {
644 2
                $resultArray[] = $compiledValueResult->getValue();
645
            }
646 3
        }
647
648 3
        return new CompiledExpression(CompiledExpression::ARR, $resultArray);
649
    }
650
651
    /**
652
     * Convert const fetch expr to CompiledExpression
653
     *
654
     * @param Node\Expr\ConstFetch $expr
655
     * @return CompiledExpression
656
     */
657
    protected function constFetch(Node\Expr\ConstFetch $expr)
658
    {
659
        if ($expr->name instanceof Node\Name) {
660
            if ($expr->name->parts[0] === 'true') {
661
                return new CompiledExpression(CompiledExpression::BOOLEAN, true);
662
            }
663
664
            if ($expr->name->parts[0] === 'false') {
665
                return new CompiledExpression(CompiledExpression::BOOLEAN, false);
666
            }
667
        }
668
669
        /**
670
         * @todo Implement check
671
         */
672
673
        $expression = new Expression($this->context);
674
        $compiledExpr = $expression->compile($expr->name);
675
676
        return $compiledExpr;
677
    }
678
}
679