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

Expression::passPropertyFetch()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 39
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 39
ccs 0
cts 29
cp 0
rs 6.7272
cc 7
eloc 27
nc 8
nop 1
crap 56
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 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, ['parent'])) {
259
            /** @var ClassDefinition $scope */
260
            $scope = $this->context->scope;
261
            assert($scope instanceof ClassDefinition);
262
263
            if ($scope->getExtendsClass()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $scope->getExtendsClass() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
264
                $definition = $scope->getExtendsClassDefinition();
265
                if ($definition) {
266
                    return new CompiledExpression(CompiledExpression::OBJECT, $definition);
267
                }
268
            } else {
269
270
            }
271
        }
272
273
        if (in_array($expr, ['self', 'static'])) {
274
            return CompiledExpression::fromZvalValue($this->context->scope);
275
        }
276
277
        $this->context->debug('[Unknown] How to get Node\Name for ' . $expr);
278
        return new CompiledExpression();
279
    }
280
281
    /**
282
     * (bool) {$expr}
283
     *
284
     * @param Node\Expr\Cast\Bool_ $expr
285
     * @return CompiledExpression
286
     */
287
    protected function passCastBoolean(Node\Expr\Cast\Bool_ $expr)
288
    {
289
        $expression = new Expression($this->context);
290
        $compiledExpression = $expression->compile($expr->expr);
291
292
        switch ($compiledExpression->getType()) {
293
            case CompiledExpression::BOOLEAN:
294
                $this->context->notice('stupid-cast', "You are trying to cast 'boolean' to 'boolean'", $expr);
295
                return $compiledExpression;
296
            case CompiledExpression::DOUBLE:
297
            case CompiledExpression::INTEGER:
298
                return new CompiledExpression(CompiledExpression::BOOLEAN, (bool) $compiledExpression->getValue());
299
        }
300
301
        return new CompiledExpression();
302
    }
303
304
    /**
305
     * (int) {$expr}
306
     *
307
     * @param Node\Expr\Cast\Int_ $expr
308
     * @return CompiledExpression
309
     */
310
    protected function passCastInt(Node\Expr\Cast\Int_ $expr)
311
    {
312
        $expression = new Expression($this->context);
313
        $compiledExpression = $expression->compile($expr->expr);
314
315
        switch ($compiledExpression->getType()) {
316
            case CompiledExpression::INTEGER:
317
                $this->context->notice('stupid-cast', "You are trying to cast 'int' to 'int'", $expr);
318
                return $compiledExpression;
319
            case CompiledExpression::BOOLEAN:
320
            case CompiledExpression::DOUBLE:
321
            case CompiledExpression::STRING:
322
                return new CompiledExpression(CompiledExpression::INTEGER, (int) $compiledExpression->getValue());
323
        }
324
325
        return new CompiledExpression();
326
    }
327
328
    /**
329
     * (float) {$expr}
330
     *
331
     * @param Node\Expr\Cast\Double $expr
332
     * @return CompiledExpression
333
     */
334
    protected function passCastFloat(Node\Expr\Cast\Double $expr)
335
    {
336
        $expression = new Expression($this->context);
337
        $compiledExpression = $expression->compile($expr->expr);
338
339
        switch ($compiledExpression->getType()) {
340
            case CompiledExpression::DOUBLE:
341
                $this->context->notice('stupid-cast', "You are trying to cast 'float' to 'float'", $expr);
342
                return $compiledExpression;
343
            case CompiledExpression::BOOLEAN:
344
            case CompiledExpression::INTEGER:
345
            case CompiledExpression::STRING:
346
                return new CompiledExpression(CompiledExpression::DOUBLE, (float) $compiledExpression->getValue());
347
        }
348
349
        return new CompiledExpression();
350
    }
351
352
    /**
353
     * (string) {$expr}
354
     *
355
     * @param Node\Expr\Cast\String_ $expr
356
     * @return CompiledExpression
357
     */
358
    protected function passCastString(Node\Expr\Cast\String_ $expr)
359
    {
360
        $expression = new Expression($this->context);
361
        $compiledExpression = $expression->compile($expr->expr);
362
363
        switch ($compiledExpression->getType()) {
364
            case CompiledExpression::STRING:
365
                $this->context->notice('stupid-cast', "You are trying to cast 'string' to 'string'", $expr);
366
                return $compiledExpression;
367
            case CompiledExpression::BOOLEAN:
368
            case CompiledExpression::INTEGER:
369
            case CompiledExpression::DOUBLE:
370
                return new CompiledExpression(CompiledExpression::DOUBLE, (string) $compiledExpression->getValue());
371
        }
372
373
        return new CompiledExpression();
374
    }
375
376
    /**
377
     * (unset) {$expr}
378
     *
379
     * @param Node\Expr\Cast\Unset_ $expr
380
     * @return CompiledExpression
381
     */
382
    protected function passCastUnset(Node\Expr\Cast\Unset_ $expr)
383
    {
384
        $expression = new Expression($this->context);
385
        $compiledExpression = $expression->compile($expr->expr);
386
387
        switch ($compiledExpression->getType()) {
388
            case CompiledExpression::NULL:
389
                $this->context->notice('stupid-cast', "You are trying to cast 'unset' to 'null'", $expr);
390
                return $compiledExpression;
391
        }
392
393
        return new CompiledExpression(CompiledExpression::NULL, null);
394
    }
395
396
    /**
397
     * @param Node\Expr\PropertyFetch $expr
398
     * @return CompiledExpression
399
     */
400
    protected function passPropertyFetch(Node\Expr\PropertyFetch $expr)
401
    {
402
        $propertNameCE = $this->compile($expr->name);
403
404
        $scopeExpression = $this->compile($expr->var);
405
        if ($scopeExpression->isObject()) {
406
            $scopeExpressionValue = $scopeExpression->getValue();
407
            if ($scopeExpressionValue instanceof ClassDefinition) {
408
                $propertyName = $propertNameCE->isString() ? $propertNameCE->getValue() : false;
409
                if ($propertyName) {
410
                    if ($scopeExpressionValue->hasProperty($propertyName, true)) {
411
                        $property = $scopeExpressionValue->getProperty($propertyName, true);
412
                        return $this->compile($property);
413
                    } else {
414
                        $this->context->notice(
415
                            'undefined-property',
416
                            sprintf(
417
                                'Property %s does not exist in %s scope',
418
                                $propertyName,
419
                                $scopeExpressionValue->getName()
420
                            ),
421
                            $expr
422
                        );
423
                    }
424
                }
425
            }
426
        } elseif (!$scopeExpression->canBeObject()) {
427
            return new CompiledExpression(CompiledExpression::UNKNOWN);
428
        }
429
430
        $this->context->notice(
431
            'property-fetch-on-non-object',
432
            "It's not possible to fetch property on not object",
433
            $expr,
434
            Check::CHECK_BETA
435
        );
436
437
        return new CompiledExpression(CompiledExpression::UNKNOWN);
438
    }
439
440
    /**
441
     * @param Node\Expr\ClassConstFetch $expr
442
     * @return CompiledExpression
443
     */
444
    protected function passConstFetch(Node\Expr\ClassConstFetch $expr)
445
    {
446
        $leftCE = $this->compile($expr->class);
447
        if ($leftCE->isObject()) {
448
            $leftCEValue = $leftCE->getValue();
449
            if ($leftCEValue instanceof ClassDefinition) {
450
                if (!$leftCEValue->hasConst($expr->name)) {
451
                    $this->context->notice(
452
                        'undefined-const',
453
                        sprintf('Constant %s does not exist in %s scope', $expr->name, $expr->class),
454
                        $expr
455
                    );
456
                    return new CompiledExpression(CompiledExpression::UNKNOWN);
457
                }
458
459
                return new CompiledExpression();
460
            }
461
        }
462
463
        $this->context->debug('Unknown const fetch');
464
        return new CompiledExpression();
465
    }
466
467
    /**
468
     * @param Node\Expr\Assign $expr
469
     * @return CompiledExpression
470
     */
471
    protected function passSymbol(Node\Expr\Assign $expr)
472
    {
473
        $expression = new Expression($this->context);
474
        $compiledExpression = $expression->compile($expr->expr);
475
476
        if ($expr->var instanceof Node\Expr\List_) {
477
            $isCorrectType = false;
478
479
            switch ($compiledExpression->getType()) {
480
                case CompiledExpression::ARR:
481
                    $isCorrectType = true;
482
                    break;
483
            }
484
485
            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...
486
                foreach ($expr->var->vars as $key => $var) {
487
                    if ($var instanceof Node\Expr\Variable) {
488
                        $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...
489
490
                        $symbol = $this->context->getSymbol($name);
491
                        if (!$symbol) {
492
                            $symbol = new Variable(
493
                                $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 488 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...
494
                                null,
495
                                CompiledExpression::UNKNOWN,
496
                                $this->context->getCurrentBranch()
497
                            );
498
                            $this->context->addVariable($symbol);
499
                        }
500
501
                        if (!$isCorrectType) {
502
                            $symbol->modify(CompiledExpression::NULL, null);
503
                        }
504
505
                        $symbol->incSets();
506
                    }
507
                }
508
            }
509
510
            return new CompiledExpression();
511
        }
512
513
        if ($expr->var instanceof Node\Expr\Variable) {
514
            $name = $expr->var->name;
515
516
            $symbol = $this->context->getSymbol($name);
517
            if ($symbol) {
518
                $symbol->modify($compiledExpression->getType(), $compiledExpression->getValue());
519
            } else {
520
                $symbol = new Variable(
521
                    $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 514 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...
522
                    $compiledExpression->getValue(),
523
                    $compiledExpression->getType(),
524
                    $this->context->getCurrentBranch()
525
                );
526
                $this->context->addVariable($symbol);
527
            }
528
529
            $symbol->incSets();
530
            return $compiledExpression;
531
        }
532
533
        if ($expr->var instanceof Node\Expr\PropertyFetch) {
534
            $compiledExpression = $this->compile($expr->var->var);
535
            if ($compiledExpression->getType() == CompiledExpression::OBJECT) {
536
                $objectDefinition = $compiledExpression->getValue();
537
                if ($objectDefinition instanceof ClassDefinition) {
538
                    if (is_string($expr->var->name)) {
539
                        if ($objectDefinition->hasProperty($expr->var->name)) {
540
                            return $this->compile($objectDefinition->getProperty($expr->var->name));
541
                        }
542
                    }
543
                }
544
            }
545
        }
546
547
        $this->context->debug('Unknown how to pass symbol');
548
        return new CompiledExpression();
549
    }
550
551
    /**
552
     * @param Node\Expr\AssignRef $expr
553
     * @return CompiledExpression
554
     */
555
    protected function passSymbolByRef(Node\Expr\AssignRef $expr)
556
    {
557
        if ($expr->var instanceof \PhpParser\Node\Expr\List_) {
558
            return new CompiledExpression();
559
        }
560
561
        if ($expr->var instanceof Node\Expr\Variable) {
562
            $name = $expr->var->name;
563
564
            $expression = new Expression($this->context);
565
            $compiledExpression = $expression->compile($expr->expr);
566
567
            $symbol = $this->context->getSymbol($name);
568
            if ($symbol) {
569
                $symbol->modify($compiledExpression->getType(), $compiledExpression->getValue());
570
571
                if ($expr->expr instanceof Node\Expr\Variable) {
572
                    $rightVarName = $expr->expr->name;
573
574
                    $rightSymbol = $this->context->getSymbol($rightVarName);
575
                    if ($rightSymbol) {
576
                        $rightSymbol->incUse();
577
                        $symbol->setReferencedTo($rightSymbol);
578
                    } else {
579
                        $this->context->debug('Cannot fetch variable by name: ' . $rightVarName);
580
                    }
581
                }
582
583
                $this->context->debug('Unknown how to pass referenced to symbol: ' . get_class($expr->expr));
584
            } else {
585
                $symbol = new Variable(
586
                    $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 562 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...
587
                    $compiledExpression->getValue(),
588
                    $compiledExpression->getType(),
589
                    $this->context->getCurrentBranch()
590
                );
591
                $this->context->addVariable($symbol);
592
            }
593
594
            $symbol->incSets();
595
            return $compiledExpression;
596
        }
597
598
        $this->context->debug('Unknown how to pass symbol by ref');
599
        return new CompiledExpression();
600
    }
601
602
    /**
603
     * @param Node\Expr\Variable $expr
604
     * @return CompiledExpression
605
     */
606
    protected function passExprVariable(Node\Expr\Variable $expr)
607
    {
608
        $variable = $this->context->getSymbol($expr->name);
609
        if ($variable) {
610
            $variable->incGets();
611
            return new CompiledExpression($variable->getType(), $variable->getValue(), $variable);
612
        }
613
614
        $this->context->notice(
615
            'undefined-variable',
616
            sprintf('You trying to use undefined variable $%s', $expr->name),
617
            $expr
618
        );
619
620
        return new CompiledExpression();
621
    }
622
623
    /**
624
     * Compile Array_ expression to CompiledExpression
625
     *
626
     * @param Node\Expr\Array_ $expr
627
     * @return CompiledExpression
628
     */
629 11
    protected function getArray(Node\Expr\Array_ $expr)
630
    {
631 11
        if ($expr->items === array()) {
632 8
            return new CompiledExpression(CompiledExpression::ARR, array());
633
        }
634
635 3
        $resultArray = array();
636
637 3
        foreach ($expr->items as $item) {
638 3
            $compiledValueResult = $this->compile($item->value);
639 3
            if ($item->key) {
640 1
                $compiledKeyResult = $this->compile($item->key);
641 1
                switch ($compiledKeyResult->getType()) {
642 1
                    case CompiledExpression::INTEGER:
643 1
                    case CompiledExpression::DOUBLE:
644 1
                    case CompiledExpression::BOOLEAN:
645 1
                    case CompiledExpression::NULL:
646 1
                    case CompiledExpression::STRING:
647 1
                        $resultArray[$compiledKeyResult->getValue()] = $compiledValueResult->getValue();
648 1
                        break;
649
                    default:
650
                        $this->context->debug("Type {$compiledKeyResult->getType()} is not supported for key value");
651
                        return new CompiledExpression(CompiledExpression::ARR);
652
                        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...
653 1
                }
654 1
            } else {
655 2
                $resultArray[] = $compiledValueResult->getValue();
656
            }
657 3
        }
658
659 3
        return new CompiledExpression(CompiledExpression::ARR, $resultArray);
660
    }
661
662
    /**
663
     * Convert const fetch expr to CompiledExpression
664
     *
665
     * @param Node\Expr\ConstFetch $expr
666
     * @return CompiledExpression
667
     */
668
    protected function constFetch(Node\Expr\ConstFetch $expr)
669
    {
670
        if ($expr->name instanceof Node\Name) {
671
            if ($expr->name->parts[0] === 'true') {
672
                return new CompiledExpression(CompiledExpression::BOOLEAN, true);
673
            }
674
675
            if ($expr->name->parts[0] === 'false') {
676
                return new CompiledExpression(CompiledExpression::BOOLEAN, false);
677
            }
678
        }
679
680
        /**
681
         * @todo Implement check
682
         */
683
684
        $expression = new Expression($this->context);
685
        $compiledExpr = $expression->compile($expr->name);
686
687
        return $compiledExpr;
688
    }
689
}
690