Completed
Push — master ( a2fcca...a1d890 )
by Дмитрий
03:20
created

Expression::compile()   D

Complexity

Conditions 26
Paths 26

Size

Total Lines 80
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 52.4057

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 80
ccs 37
cts 56
cp 0.6606
rs 4.9736
cc 26
eloc 57
nc 26
nop 1
crap 52.4057

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 134 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 640 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_null($expr)) {
145
            return new CompiledExpression(CompiledExpression::NULL);
146
        }
147
148 363
        if (!is_object($expr)) {
149
            throw new InvalidArgumentException('$expr must be string/object/null');
150
        }
151
152 363
        $className = get_class($expr);
153
        switch ($className) {
154 363
            case 'PhpParser\Node\Expr\PropertyFetch':
155
                return $this->passPropertyFetch($expr);
156 363
            case 'PhpParser\Node\Stmt\Property':
157
                return $this->passProperty($expr);
158 363
            case 'PhpParser\Node\Expr\ClassConstFetch':
159
                return $this->passConstFetch($expr);
160 363
            case 'PhpParser\Node\Expr\Assign':
161
                return $this->passSymbol($expr);
162 363
            case 'PhpParser\Node\Expr\AssignRef':
163
                return $this->passSymbolByRef($expr);
164 363
            case 'PhpParser\Node\Expr\Variable':
165
                return $this->passExprVariable($expr);
166
            /**
167
             * Cast operators
168
             */
169 363
            case 'PhpParser\Node\Expr\Cast\Bool_':
170
                return $this->passCastBoolean($expr);
171 363
            case 'PhpParser\Node\Expr\Cast\Int_':
172
                return $this->passCastInt($expr);
173 363
            case 'PhpParser\Node\Expr\Cast\Double':
174
                return $this->passCastFloat($expr);
175 363
            case 'PhpParser\Node\Expr\Cast\String_':
176
                return $this->passCastString($expr);
177 363
            case 'PhpParser\Node\Expr\Cast\Unset_':
178
                return $this->passCastUnset($expr);
179
            /**
180
             * Expressions
181
             */
182 363
            case 'PhpParser\Node\Expr\Array_':
183 11
                return $this->getArray($expr);
184 362
            case 'PhpParser\Node\Expr\ConstFetch':
185
                return $this->constFetch($expr);
186 362
            case 'PhpParser\Node\Name':
187
                return $this->getNodeName($expr);
188
            /**
189
             * Simple Scalar(s)
190
             */
191 362
            case 'PHPSA\Node\Scalar\Nil':
192 8
                return new CompiledExpression(CompiledExpression::NULL);
193 361
            case 'PhpParser\Node\Scalar\LNumber':
194 256
                return new CompiledExpression(CompiledExpression::INTEGER, $expr->value);
195 358
            case 'PhpParser\Node\Scalar\DNumber':
196 131
                return new CompiledExpression(CompiledExpression::DOUBLE, $expr->value);
197 357
            case 'PhpParser\Node\Scalar\String_':
198 8
                return new CompiledExpression(CompiledExpression::STRING, $expr->value);
199 355
            case 'PHPSA\Node\Scalar\Boolean':
200 60
                return new CompiledExpression(CompiledExpression::BOOLEAN, $expr->value);
201 353
            case 'PHPSA\Node\Scalar\Fake':
202 29
                return new CompiledExpression($expr->type, $expr->value);
203
        }
204
205 353
        $expressionCompiler = $this->factory($expr);
206 353
        if (!$expressionCompiler) {
207
            $this->context->debug("Expression compiler is not implemented for {$className}");
208
            return new CompiledExpression(CompiledExpression::UNIMPLEMENTED);
209
        }
210
211 353
        $result = $expressionCompiler->pass($expr, $this->context);
212 353
        if (!$result instanceof CompiledExpression) {
213
            throw new RuntimeException('Please return CompiledExpression from ' . get_class($expressionCompiler));
214
        }
215
216 353
        return $result;
217
    }
218
219
    /**
220
     * @todo Implement
221
     *
222
     * @param Node\Stmt\Property $st
223
     * @return CompiledExpression
224
     */
225
    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...
226
    {
227
        return new CompiledExpression();
228
    }
229
230
    /**
231
     * @param Node\Expr\Variable $expr
232
     * @return CompiledExpression
233
     */
234
    public function declareVariable(Node\Expr\Variable $expr)
235
    {
236
        $variable = $this->context->getSymbol($expr->name);
237
        if ($variable) {
238
            $variable->incGets();
239
            return new CompiledExpression($variable->getType(), $variable->getValue(), $variable);
240
        }
241
242
        $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...
243
        $this->context->addVariable($symbol);
244
245
        return new CompiledExpression;
246
    }
247
248
    /**
249
     * @param Node\Name $expr
250
     * @return CompiledExpression
251
     */
252
    public function getNodeName(Node\Name $expr)
253
    {
254
        if ($expr->parts[0] === 'null') {
255
            return new CompiledExpression(CompiledExpression::NULL);
256
        }
257
258
        if (in_array($expr, ['self', 'static'])) {
259
            return CompiledExpression::fromZvalValue($this->context->scope);
260
//            $scopePointer = $this->context->scopePointer;
261
//            if ($scopePointer) {
262
//                if ($scopePointer->isClassMethod()) {
263
//                    $classMethod = $scopePointer->getObject();
264
//                    if ($classMethod && $classMethod->isStatic()) {
265
//                        return CompiledExpression::fromZvalValue($this->context->scope);
266
//                    }
267
//                }
268
//            }
269
        }
270
271
        $this->context->debug('[Unknown] How to get Node\Name for ' . $expr);
272
        return new CompiledExpression();
273
    }
274
275
    /**
276
     * (bool) {$expr}
277
     *
278
     * @param Node\Expr\Cast\Bool_ $expr
279
     * @return CompiledExpression
280
     */
281
    protected function passCastBoolean(Node\Expr\Cast\Bool_ $expr)
282
    {
283
        $expression = new Expression($this->context);
284
        $compiledExpression = $expression->compile($expr->expr);
285
286
        switch ($compiledExpression->getType()) {
287
            case CompiledExpression::BOOLEAN:
288
                $this->context->notice('stupid-cast', "You are trying to cast 'boolean' to 'boolean'", $expr);
289
                return $compiledExpression;
290
            case CompiledExpression::DOUBLE:
291
            case CompiledExpression::INTEGER:
292
                return new CompiledExpression(CompiledExpression::BOOLEAN, (bool) $compiledExpression->getValue());
293
        }
294
295
        return new CompiledExpression();
296
    }
297
298
    /**
299
     * (int) {$expr}
300
     *
301
     * @param Node\Expr\Cast\Int_ $expr
302
     * @return CompiledExpression
303
     */
304
    protected function passCastInt(Node\Expr\Cast\Int_ $expr)
305
    {
306
        $expression = new Expression($this->context);
307
        $compiledExpression = $expression->compile($expr->expr);
308
309
        switch ($compiledExpression->getType()) {
310
            case CompiledExpression::INTEGER:
311
                $this->context->notice('stupid-cast', "You are trying to cast 'int' to 'int'", $expr);
312
                return $compiledExpression;
313
            case CompiledExpression::BOOLEAN:
314
            case CompiledExpression::DOUBLE:
315
            case CompiledExpression::STRING:
316
                return new CompiledExpression(CompiledExpression::INTEGER, (int) $compiledExpression->getValue());
317
        }
318
319
        return new CompiledExpression();
320
    }
321
322
    /**
323
     * (float) {$expr}
324
     *
325
     * @param Node\Expr\Cast\Double $expr
326
     * @return CompiledExpression
327
     */
328
    protected function passCastFloat(Node\Expr\Cast\Double $expr)
329
    {
330
        $expression = new Expression($this->context);
331
        $compiledExpression = $expression->compile($expr->expr);
332
333
        switch ($compiledExpression->getType()) {
334
            case CompiledExpression::DOUBLE:
335
                $this->context->notice('stupid-cast', "You are trying to cast 'float' to 'float'", $expr);
336
                return $compiledExpression;
337
            case CompiledExpression::BOOLEAN:
338
            case CompiledExpression::INTEGER:
339
            case CompiledExpression::STRING:
340
                return new CompiledExpression(CompiledExpression::DOUBLE, (float) $compiledExpression->getValue());
341
        }
342
343
        return new CompiledExpression();
344
    }
345
346
    /**
347
     * (string) {$expr}
348
     *
349
     * @param Node\Expr\Cast\String_ $expr
350
     * @return CompiledExpression
351
     */
352
    protected function passCastString(Node\Expr\Cast\String_ $expr)
353
    {
354
        $expression = new Expression($this->context);
355
        $compiledExpression = $expression->compile($expr->expr);
356
357
        switch ($compiledExpression->getType()) {
358
            case CompiledExpression::STRING:
359
                $this->context->notice('stupid-cast', "You are trying to cast 'string' to 'string'", $expr);
360
                return $compiledExpression;
361
            case CompiledExpression::BOOLEAN:
362
            case CompiledExpression::INTEGER:
363
            case CompiledExpression::DOUBLE:
364
                return new CompiledExpression(CompiledExpression::DOUBLE, (string) $compiledExpression->getValue());
365
        }
366
367
        return new CompiledExpression();
368
    }
369
370
    /**
371
     * (unset) {$expr}
372
     *
373
     * @param Node\Expr\Cast\Unset_ $expr
374
     * @return CompiledExpression
375
     */
376
    protected function passCastUnset(Node\Expr\Cast\Unset_ $expr)
377
    {
378
        $expression = new Expression($this->context);
379
        $compiledExpression = $expression->compile($expr->expr);
380
381
        switch ($compiledExpression->getType()) {
382
            case CompiledExpression::NULL:
383
                $this->context->notice('stupid-cast', "You are trying to cast 'unset' to 'null'", $expr);
384
                return $compiledExpression;
385
        }
386
387
        return new CompiledExpression(CompiledExpression::NULL, null);
388
    }
389
390
    /**
391
     * @param Node\Expr\PropertyFetch $expr
392
     * @return CompiledExpression
393
     */
394
    protected function passPropertyFetch(Node\Expr\PropertyFetch $expr)
395
    {
396
        $propertNameCE = $this->compile($expr->name);
397
398
        $scopeExpression = $this->compile($expr->var);
399
        if ($scopeExpression->isObject()) {
400
            $scopeExpressionValue = $scopeExpression->getValue();
401
            if ($scopeExpressionValue instanceof ClassDefinition) {
402
                $propertyName = $propertNameCE->isString() ? $propertNameCE->getValue() : false;
403
                if ($propertyName) {
404
                    if ($scopeExpressionValue->hasProperty($propertyName, true)) {
405
                        $property = $scopeExpressionValue->getProperty($propertyName, true);
406
                        return $this->compile($property);
407
                    } else {
408
                        $this->context->notice(
409
                            'undefined-property',
410
                            sprintf(
411
                                'Property %s does not exist in %s scope',
412
                                $propertyName,
413
                                $scopeExpressionValue->getName()
414
                            ),
415
                            $expr
416
                        );
417
                    }
418
                }
419
            }
420
        } elseif (!$scopeExpression->canBeObject()) {
421
            return new CompiledExpression(CompiledExpression::UNKNOWN);
422
        }
423
424
        $this->context->notice(
425
            'property-fetch-on-non-object',
426
            "It's not possible to fetch property on not object",
427
            $expr,
428
            Check::CHECK_BETA
429
        );
430
431
        return new CompiledExpression(CompiledExpression::UNKNOWN);
432
    }
433
434
    /**
435
     * @param Node\Expr\ClassConstFetch $expr
436
     * @return CompiledExpression
437
     */
438
    protected function passConstFetch(Node\Expr\ClassConstFetch $expr)
439
    {
440
        $leftCE = $this->compile($expr->class);
441
        if ($leftCE->isObject()) {
442
            $leftCEValue = $leftCE->getValue();
443
            if ($leftCEValue instanceof ClassDefinition) {
444
                if (!$leftCEValue->hasConst($expr->name)) {
445
                    $this->context->notice(
446
                        'undefined-const',
447
                        sprintf('Constant %s does not exist in %s scope', $expr->name, $expr->class),
448
                        $expr
449
                    );
450
                    return new CompiledExpression(CompiledExpression::UNKNOWN);
451
                }
452
453
                return new CompiledExpression();
454
            }
455
        }
456
457
        $this->context->debug('Unknown const fetch');
458
        return new CompiledExpression();
459
    }
460
461
    /**
462
     * @param Node\Expr\Assign $expr
463
     * @return CompiledExpression
464
     */
465
    protected function passSymbol(Node\Expr\Assign $expr)
466
    {
467
        $expression = new Expression($this->context);
468
        $compiledExpression = $expression->compile($expr->expr);
469
470
        if ($expr->var instanceof Node\Expr\List_) {
471
            $isCorrectType = false;
472
473
            switch ($compiledExpression->getType()) {
474
                case CompiledExpression::ARR:
475
                    $isCorrectType = true;
476
                    break;
477
            }
478
479
            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...
480
                foreach ($expr->var->vars as $key => $var) {
481
                    if ($var instanceof Node\Expr\Variable) {
482
                        $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...
483
484
                        $symbol = $this->context->getSymbol($name);
485
                        if (!$symbol) {
486
                            $symbol = new Variable(
487
                                $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 482 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...
488
                                null,
489
                                CompiledExpression::UNKNOWN,
490
                                $this->context->getCurrentBranch()
491
                            );
492
                            $this->context->addVariable($symbol);
493
                        }
494
495
                        if (!$isCorrectType) {
496
                            $symbol->modify(CompiledExpression::NULL, null);
497
                        }
498
499
                        $symbol->incSets();
500
                    }
501
                }
502
            }
503
504
            return new CompiledExpression();
505
        }
506
507
        if ($expr->var instanceof Node\Expr\Variable) {
508
            $name = $expr->var->name;
509
510
            $symbol = $this->context->getSymbol($name);
511
            if ($symbol) {
512
                $symbol->modify($compiledExpression->getType(), $compiledExpression->getValue());
513
            } else {
514
                $symbol = new Variable(
515
                    $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 508 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...
516
                    $compiledExpression->getValue(),
517
                    $compiledExpression->getType(),
518
                    $this->context->getCurrentBranch()
519
                );
520
                $this->context->addVariable($symbol);
521
            }
522
523
            $symbol->incSets();
524
            return $compiledExpression;
525
        }
526
527
        if ($expr->var instanceof Node\Expr\PropertyFetch) {
528
            $compiledExpression = $this->compile($expr->var->var);
529
            if ($compiledExpression->getType() == CompiledExpression::OBJECT) {
530
                $objectDefinition = $compiledExpression->getValue();
531
                if ($objectDefinition instanceof ClassDefinition) {
532
                    if (is_string($expr->var->name)) {
533
                        if ($objectDefinition->hasProperty($expr->var->name)) {
534
                            return $this->compile($objectDefinition->getProperty($expr->var->name));
535
                        }
536
                    }
537
                }
538
            }
539
        }
540
541
        $this->context->debug('Unknown how to pass symbol');
542
        return new CompiledExpression();
543
    }
544
545
    /**
546
     * @param Node\Expr\AssignRef $expr
547
     * @return CompiledExpression
548
     */
549
    protected function passSymbolByRef(Node\Expr\AssignRef $expr)
550
    {
551
        if ($expr->var instanceof \PhpParser\Node\Expr\List_) {
552
            return new CompiledExpression();
553
        }
554
555
        if ($expr->var instanceof Node\Expr\Variable) {
556
            $name = $expr->var->name;
557
558
            $expression = new Expression($this->context);
559
            $compiledExpression = $expression->compile($expr->expr);
560
561
            $symbol = $this->context->getSymbol($name);
562
            if ($symbol) {
563
                $symbol->modify($compiledExpression->getType(), $compiledExpression->getValue());
564
565
                if ($expr->expr instanceof Node\Expr\Variable) {
566
                    $rightVarName = $expr->expr->name;
567
568
                    $rightSymbol = $this->context->getSymbol($rightVarName);
569
                    if ($rightSymbol) {
570
                        $rightSymbol->incUse();
571
                        $symbol->setReferencedTo($rightSymbol);
572
                    } else {
573
                        $this->context->debug('Cannot fetch variable by name: ' . $rightVarName);
574
                    }
575
                }
576
577
                $this->context->debug('Unknown how to pass referenced to symbol: ' . get_class($expr->expr));
578
            } else {
579
                $symbol = new Variable(
580
                    $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 556 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...
581
                    $compiledExpression->getValue(),
582
                    $compiledExpression->getType(),
583
                    $this->context->getCurrentBranch()
584
                );
585
                $this->context->addVariable($symbol);
586
            }
587
588
            $symbol->incSets();
589
            return $compiledExpression;
590
        }
591
592
        $this->context->debug('Unknown how to pass symbol by ref');
593
        return new CompiledExpression();
594
    }
595
596
    /**
597
     * @param Node\Expr\Variable $expr
598
     * @return CompiledExpression
599
     */
600
    protected function passExprVariable(Node\Expr\Variable $expr)
601
    {
602
        $variable = $this->context->getSymbol($expr->name);
603
        if ($variable) {
604
            $variable->incGets();
605
            return new CompiledExpression($variable->getType(), $variable->getValue(), $variable);
606
        }
607
608
        $this->context->notice(
609
            'undefined-variable',
610
            sprintf('You trying to use undefined variable $%s', $expr->name),
611
            $expr
612
        );
613
614
        return new CompiledExpression();
615
    }
616
617
    /**
618
     * Compile Array_ expression to CompiledExpression
619
     *
620
     * @param Node\Expr\Array_ $expr
621
     * @return CompiledExpression
622
     */
623 11
    protected function getArray(Node\Expr\Array_ $expr)
624
    {
625 11
        if ($expr->items === array()) {
626 8
            return new CompiledExpression(CompiledExpression::ARR, array());
627
        }
628
629 3
        $resultArray = array();
630
631 3
        foreach ($expr->items as $item) {
632 3
            $compiledValueResult = $this->compile($item->value);
633 3
            if ($item->key) {
634 1
                $compiledKeyResult = $this->compile($item->key);
635 1
                switch ($compiledKeyResult->getType()) {
636 1
                    case CompiledExpression::INTEGER:
637 1
                    case CompiledExpression::DOUBLE:
638 1
                    case CompiledExpression::BOOLEAN:
639 1
                    case CompiledExpression::NULL:
640 1
                    case CompiledExpression::STRING:
641 1
                        $resultArray[$compiledKeyResult->getValue()] = $compiledValueResult->getValue();
642 1
                        break;
643
                    default:
644
                        $this->context->debug("Type {$compiledKeyResult->getType()} is not supported for key value");
645
                        return new CompiledExpression(CompiledExpression::ARR);
646
                        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...
647 1
                }
648 1
            } else {
649 2
                $resultArray[] = $compiledValueResult->getValue();
650
            }
651 3
        }
652
653 3
        return new CompiledExpression(CompiledExpression::ARR, $resultArray);
654
    }
655
656
    /**
657
     * Convert const fetch expr to CompiledExpression
658
     *
659
     * @param Node\Expr\ConstFetch $expr
660
     * @return CompiledExpression
661
     */
662
    protected function constFetch(Node\Expr\ConstFetch $expr)
663
    {
664
        if ($expr->name instanceof Node\Name) {
665
            if ($expr->name->parts[0] === 'true') {
666
                return new CompiledExpression(CompiledExpression::BOOLEAN, true);
667
            }
668
669
            if ($expr->name->parts[0] === 'false') {
670
                return new CompiledExpression(CompiledExpression::BOOLEAN, false);
671
            }
672
        }
673
674
        /**
675
         * @todo Implement check
676
         */
677
678
        $expression = new Expression($this->context);
679
        $compiledExpr = $expression->compile($expr->name);
680
681
        return $compiledExpr;
682
    }
683
}
684