Completed
Pull Request — master (#196)
by Enrico
06:58
created

Expression::compile()   C

Complexity

Conditions 19
Paths 19

Size

Total Lines 76
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 42
CRAP Score 20.0534

Importance

Changes 0
Metric Value
cc 19
eloc 48
nc 19
nop 1
dl 0
loc 76
ccs 42
cts 49
cp 0.8571
crap 20.0534
rs 5.222
c 0
b 0
f 0

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 phpDocumentor\Reflection\DocBlockFactory;
10
use PHPSA\Check;
11
use PHPSA\CompiledExpression;
12
use PHPSA\Compiler\Event\ExpressionBeforeCompile;
13
use PHPSA\Context;
14
use PhpParser\Node;
15
use PHPSA\Definition\ClassDefinition;
16
use PHPSA\Exception\RuntimeException;
17
use PHPSA\Variable;
18
use PHPSA\Compiler\Expression\AbstractExpressionCompiler;
19
use Webiny\Component\EventManager\EventManager;
20
21
class Expression
0 ignored issues
show
Complexity introduced by
This class has a complexity of 142 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...
22
{
23
    /**
24
     * @var Context
25
     */
26
    protected $context;
27
28
    /**
29
     * @var EventManager
30
     */
31
    protected $eventManager;
32
33
    /**
34
     * @param Context $context
35
     */
36 848
    public function __construct(Context $context, EventManager $eventManager)
37
    {
38 848
        $this->context = $context;
39 848
        $this->eventManager = $eventManager;
40 848
    }
41
42
    /**
43
     * @param $expr
44
     * @return ExpressionCompilerInterface|AbstractExpressionCompiler
45
     */
46 828
    protected function factory($expr)
47
    {
48 828
        switch (get_class($expr)) {
49
            /**
50
             * Call(s)
51
             */
52 828
            case Node\Expr\MethodCall::class:
53
                return new Expression\MethodCall();
54 828
            case Node\Expr\FuncCall::class:
55 10
                return new Expression\FunctionCall();
56 824
            case Node\Expr\StaticCall::class:
57 1
                return new Expression\StaticCall();
58
            /**
59
             * Operators
60
             */
61 823
            case Node\Expr\New_::class:
62 2
                return new Expression\Operators\NewOp();
63 823
            case Node\Expr\Instanceof_::class:
64
                return new Expression\Operators\InstanceOfOp();
65
            /**
66
             * AssignOp
67
             */
68 823
            case Node\Expr\AssignOp\Pow::class:
69 21
                return new Expression\AssignOp\Pow();
70 802
            case Node\Expr\AssignOp\Plus::class:
71 17
                return new Expression\AssignOp\Plus();
72 785
            case Node\Expr\AssignOp\Minus::class:
73 20
                return new Expression\AssignOp\Minus();
74 765
            case Node\Expr\AssignOp\Mul::class:
75 20
                return new Expression\AssignOp\Mul();
76 745
            case Node\Expr\AssignOp\Div::class:
77 18
                return new Expression\AssignOp\Div();
78 727
            case Node\Expr\AssignOp\Mod::class:
79 11
                return new Expression\AssignOp\Mod();
80 716
            case Node\Expr\AssignOp\BitwiseOr::class:
81 12
                return new Expression\AssignOp\BitwiseOr();
82 704
            case Node\Expr\AssignOp\BitwiseAnd::class:
83 12
                return new Expression\AssignOp\BitwiseAnd();
84 692
            case Node\Expr\AssignOp\BitwiseXor::class:
85 12
                return new Expression\AssignOp\BitwiseXor();
86 680
            case Node\Expr\AssignOp\Concat::class:
87 14
                return new Expression\AssignOp\Concat();
88 666
            case Node\Expr\AssignOp\ShiftLeft::class:
89 12
                return new Expression\AssignOp\ShiftLeft();
90 654
            case Node\Expr\AssignOp\ShiftRight::class:
91 12
                return new Expression\AssignOp\ShiftRight();
92
93
            /**
94
             * BinaryOp
95
             */
96 642
            case Node\Expr\BinaryOp\Identical::class:
97 28
                return new Expression\BinaryOp\Identical();
98 614
            case Node\Expr\BinaryOp\Concat::class:
99 15
                return new Expression\Operators\Concat();
100 600
            case Node\Expr\BinaryOp\NotIdentical::class:
101 14
                return new Expression\BinaryOp\NotIdentical();
102 586
            case Node\Expr\BinaryOp\Equal::class:
103 42
                return new Expression\BinaryOp\Equal();
104 552
            case Node\Expr\BinaryOp\NotEqual::class:
105 17
                return new Expression\BinaryOp\NotEqual();
106 535
            case Node\Expr\BinaryOp\Spaceship::class:
107 11
                return new Expression\BinaryOp\SpaceShip();
108 526
            case Node\Expr\BinaryOp\Coalesce::class:
109 3
                return new Expression\BinaryOp\Coalesce();
110
                
111
            /**
112
             * @link http://php.net/manual/en/language.operators.increment.php
113
             */
114 524
            case Node\Expr\PostInc::class:
115 8
                return new Expression\Operators\PostInc();
116 516
            case Node\Expr\PostDec::class:
117 8
                return new Expression\Operators\PostDec();
118 508
            case Node\Expr\PreInc::class:
119 8
                return new Expression\Operators\PreInc();
120 500
            case Node\Expr\PreDec::class:
121 8
                return new Expression\Operators\PreDec();
122
            /**
123
             * Arithmetical
124
             */
125 492
            case Node\Expr\BinaryOp\Div::class:
126 37
                return new Expression\Operators\Arithmetical\Div();
127 455
            case Node\Expr\BinaryOp\Plus::class:
128 45
                return new Expression\Operators\Arithmetical\Plus();
129 412
            case Node\Expr\BinaryOp\Minus::class:
130 24
                return new Expression\Operators\Arithmetical\Minus();
131 388
            case Node\Expr\BinaryOp\Mul::class:
132 35
                return new Expression\Operators\Arithmetical\Mul();
133 353
            case Node\Expr\BinaryOp\Mod::class:
134 35
                return new Expression\Operators\Arithmetical\Mod();
135 318
            case Node\Expr\BinaryOp\Pow::class:
136 21
                return new Expression\Operators\Arithmetical\Pow();
137
138
            /**
139
             * Bitwise
140
             * @link http://php.net/manual/ru/language.operators.bitwise.php
141
             */
142 297
            case Node\Expr\BinaryOp\BitwiseOr::class:
143 12
                return new Expression\Operators\Bitwise\BitwiseOr();
144 285
            case Node\Expr\BinaryOp\BitwiseXor::class:
145 12
                return new Expression\Operators\Bitwise\BitwiseXor();
146 273
            case Node\Expr\BinaryOp\BitwiseAnd::class:
147 12
                return new Expression\Operators\Bitwise\BitwiseAnd();
148 261
            case Node\Expr\BinaryOp\ShiftRight::class:
149 12
                return new Expression\Operators\Bitwise\ShiftRight();
150 249
            case Node\Expr\BinaryOp\ShiftLeft::class:
151 12
                return new Expression\Operators\Bitwise\ShiftLeft();
152 237
            case Node\Expr\BitwiseNot::class:
153 5
                return new Expression\Operators\Bitwise\BitwiseNot();
154
            /**
155
             * Logical
156
             */
157 232
            case Node\Expr\BinaryOp\BooleanOr::class:
158 17
                return new Expression\Operators\Logical\BooleanOr();
159 217
            case Node\Expr\BinaryOp\BooleanAnd::class:
160 15
                return new Expression\Operators\Logical\BooleanAnd();
161 204
            case Node\Expr\BooleanNot::class:
162 9
                return new Expression\Operators\Logical\BooleanNot();
163 196
            case Node\Expr\BinaryOp\LogicalAnd::class:
164 15
                return new Expression\Operators\Logical\LogicalAnd();
165 183
            case Node\Expr\BinaryOp\LogicalOr::class:
166 17
                return new Expression\Operators\Logical\LogicalOr();
167 168
            case Node\Expr\BinaryOp\LogicalXor::class:
168 17
                return new Expression\Operators\Logical\LogicalXor();
169
170
            /**
171
             * Comparison
172
             */
173 153
            case Node\Expr\BinaryOp\Greater::class:
174 12
                return new Expression\Operators\Comparison\Greater();
175 141
            case Node\Expr\BinaryOp\GreaterOrEqual::class:
176 12
                return new Expression\Operators\Comparison\GreaterOrEqual();
177 129
            case Node\Expr\BinaryOp\Smaller::class:
178 12
                return new Expression\Operators\Comparison\Smaller();
179 117
            case Node\Expr\BinaryOp\SmallerOrEqual::class:
180 12
                return new Expression\Operators\Comparison\SmallerOrEqual();
181
182
            /**
183
             * Casts
184
             */
185 105
            case Node\Expr\Cast\Array_::class:
186 3
                return new Expression\Casts\ArrayCast();
187 104
            case Node\Expr\Cast\Bool_::class:
188 8
                return new Expression\Casts\BoolCast();
189 98
            case Node\Expr\Cast\Int_::class:
190 8
                return new Expression\Casts\IntCast();
191 92
            case Node\Expr\Cast\Double::class:
192 8
                return new Expression\Casts\DoubleCast();
193 86
            case Node\Expr\Cast\Object_::class:
194 2
                return new Expression\Casts\ObjectCast();
195 85
            case Node\Expr\Cast\String_::class:
196 7
                return new Expression\Casts\StringCast();
197 79
            case Node\Expr\Cast\Unset_::class:
198 2
                return new Expression\Casts\UnsetCast();
199
200
201
            /**
202
             * Other
203
             */
204 78
            case Node\Expr\Array_::class:
205 36
                return new Expression\ArrayOp();
206 50
            case Node\Expr\Closure::class:
207
                return new Expression\Closure();
208 50
            case Node\Expr\ConstFetch::class:
209 7
                return new Expression\ConstFetch();
210 47
            case Node\Expr\ClassConstFetch::class:
211
                return new Expression\ClassConstFetch();
212 47
            case Node\Expr\UnaryMinus::class:
213 9
                return new Expression\Operators\UnaryMinus();
214 38
            case Node\Expr\UnaryPlus::class:
215 9
                return new Expression\Operators\UnaryPlus();
216 29
            case Node\Expr\Exit_::class:
217 1
                return new Expression\ExitOp();
218 28
            case Node\Expr\Isset_::class:
219 3
                return new Expression\IssetOp();
220 25
            case Node\Expr\Print_::class:
221 2
                return new Expression\PrintOp();
222 24
            case Node\Expr\Empty_::class:
223 5
                return new Expression\EmptyOp();
224 19
            case Node\Expr\Eval_::class:
225 2
                return new Expression\EvalOp();
226 17
            case Node\Expr\ErrorSuppress::class:
227 2
                return new Expression\ErrorSuppress();
228 15
            case Node\Expr\Clone_::class:
229 1
                return new Expression\CloneOp();
230 14
            case Node\Expr\Ternary::class:
231 2
                return new Expression\Ternary();
232 12
            case Node\Expr\Variable::class:
233 12
                return new Expression\Variable();
234
        }
235
236
        return false;
237
    }
238
239
    /**
240
     * @param object|string $expr
241
     * @throws InvalidArgumentException when $expr is not string/object/null
242
     * @throws RuntimeException when compiler class does not return a CompiledExpression
243
     * @return CompiledExpression
244
     */
245 848
    public function compile($expr)
0 ignored issues
show
Complexity introduced by
This operation has 416 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...
246
    {
247 848
        if (is_string($expr)) {
248 16
            return new CompiledExpression(CompiledExpression::STRING, $expr);
249
        }
250
251 848
        if (is_null($expr)) {
252 8
            return new CompiledExpression(CompiledExpression::NULL);
253
        }
254
255 848
        if (!is_object($expr)) {
256
            throw new InvalidArgumentException('$expr must be string/object/null');
257
        }
258
259 848
        $this->eventManager->fire(
260 848
            ExpressionBeforeCompile::EVENT_NAME,
261 848
            new ExpressionBeforeCompile(
262 848
                $expr,
263 848
                $this->context
264 848
            )
265 848
        );
266
267 848
        $className = get_class($expr);
268
        switch ($className) {
269 848
            case Node\Arg::class:
270
                /**
271
                 * @todo Better compile
272
                 */
273 2
                return $this->compile($expr->value);
274 848
            case Node\Expr\PropertyFetch::class:
275
                return $this->passPropertyFetch($expr);
276 848
            case Node\Stmt\Property::class:
277
                return $this->passProperty($expr);
278 848
            case Node\Expr\Assign::class:
279 29
                return $this->passSymbol($expr);
280 848
            case Node\Expr\AssignRef::class:
281 1
                return $this->passSymbolByRef($expr);
282
283
            /**
284
             * Expressions
285
             */
286 848
            case Node\Name::class:
287 27
                return $this->getNodeName($expr);
288 848
            case Node\Name\FullyQualified::class:
289
                return $this->getFullyQualifiedNodeName($expr);
290
291
            /**
292
             * Simple Scalar(s)
293
             */
294 848
            case \PHPSA\Node\Scalar\Nil::class:
295 25
                return new CompiledExpression(CompiledExpression::NULL);
296 847
            case Node\Scalar\LNumber::class:
297 511
                return new CompiledExpression(CompiledExpression::INTEGER, $expr->value);
298 832
            case Node\Scalar\DNumber::class:
299 212
                return new CompiledExpression(CompiledExpression::DOUBLE, $expr->value);
300 831
            case Node\Scalar\String_::class:
301 50
                return new CompiledExpression(CompiledExpression::STRING, $expr->value);
302 830
            case \PHPSA\Node\Scalar\Boolean::class:
303 241
                return new CompiledExpression(CompiledExpression::BOOLEAN, $expr->value);
304 828
            case \PHPSA\Node\Scalar\Fake::class:
305 79
                return new CompiledExpression($expr->type, $expr->value);
306
        }
307
308 828
        $expressionCompiler = $this->factory($expr);
309 828
        if (!$expressionCompiler) {
310
            $this->context->debug("Expression compiler is not implemented for {$className}");
311
            return new CompiledExpression(CompiledExpression::UNIMPLEMENTED);
312
        }
313
314 828
        $result = $expressionCompiler->pass($expr, $this->context);
315 828
        if (!$result instanceof CompiledExpression) {
316
            throw new RuntimeException('Please return CompiledExpression from ' . get_class($expressionCompiler));
317
        }
318
319 828
        return $result;
320
    }
321
322
    /**
323
     * @todo Implement
324
     *
325
     * @param Node\Stmt\Property $st
326
     * @return CompiledExpression
327
     */
328
    public function passProperty(Node\Stmt\Property $st)
0 ignored issues
show
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...
329
    {
330
        $docBlock = $st->getDocComment();
331
        if (!$docBlock) {
332
            $this->context->notice(
333
                'missing-docblock',
334
                sprintf('Missing docblock for $%s property', $st->props[0]->name),
335
                $st
336
            );
337
338
            return new CompiledExpression();
339
        }
340
341
        $phpdoc = DocBlockFactory::createInstance()->create($docBlock->getText());
342
343
        $varTags = $phpdoc->getTagsByName('var');
344
        if ($varTags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $varTags of type phpDocumentor\Reflection\DocBlock\Tag[] 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...
345
            /** @var \phpDocumentor\Reflection\DocBlock\Tag\VarTag $varTag */
346
            $varTag = current($varTags);
347
348
            $typeResolver = new \phpDocumentor\Reflection\TypeResolver();
349
350
            try {
351
                $type = $typeResolver->resolve($varTag->getType());
352
            } catch (\InvalidArgumentException $e) {
353
                return new CompiledExpression();
354
            }
355
356
            if ($type) {
357
                switch (get_class($type)) {
358
                    case \phpDocumentor\Reflection\Types\Object_::class:
359
                        return new CompiledExpression(
360
                            CompiledExpression::OBJECT
361
                        );
362
                    case \phpDocumentor\Reflection\Types\Integer::class:
363
                        return new CompiledExpression(
364
                            CompiledExpression::INTEGER
365
                        );
366
                    case \phpDocumentor\Reflection\Types\String_::class:
367
                        return new CompiledExpression(
368
                            CompiledExpression::STRING
369
                        );
370
                    case \phpDocumentor\Reflection\Types\Float_::class:
371
                        return new CompiledExpression(
372
                            CompiledExpression::DOUBLE
373
                        );
374
                    case \phpDocumentor\Reflection\Types\Null_::class:
375
                        return new CompiledExpression(
376
                            CompiledExpression::NULL
377
                        );
378
                    case \phpDocumentor\Reflection\Types\Boolean::class:
379
                        return new CompiledExpression(
380
                            CompiledExpression::BOOLEAN
381
                        );
382
                }
383
            }
384
        }
385
386
        return new CompiledExpression();
387
    }
388
389
    /**
390
     * @param Node\Expr\Variable $expr
391
     * @param mixed $value
392
     * @param int $type
393
     * @return CompiledExpression
394
     */
395 1
    public function declareVariable(Node\Expr\Variable $expr, $value = null, $type = CompiledExpression::UNKNOWN)
396
    {
397 1
        $variable = $this->context->getSymbol($expr->name);
398 1
        if (!$variable) {
399 1
            $variable = new Variable($expr->name, $value, $type, $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...
400 1
            $this->context->addVariable($variable);
401 1
        }
402
403 1
        return new CompiledExpression($variable->getType(), $variable->getValue(), $variable);
404
    }
405
406
    /**
407
     * @param Node\Name\FullyQualified $expr
408
     * @return CompiledExpression
409
     */
410
    public function getFullyQualifiedNodeName(Node\Name\FullyQualified $expr)
411
    {
412
        $this->context->debug('Unimplemented FullyQualified', $expr);
413
414
        return new CompiledExpression;
415
    }
416
417
    /**
418
     * @param Node\Name $expr
419
     * @return CompiledExpression
420
     */
421 27
    public function getNodeName(Node\Name $expr)
422
    {
423 27
        $nodeString = $expr->toString();
424 27
        if ($nodeString === 'null') {
425 1
            return new CompiledExpression(CompiledExpression::NULL);
426
        }
427
428 27
        if (in_array($nodeString, ['parent'], true)) {
429
            /** @var ClassDefinition $scope */
430
            $scope = $this->context->scope;
431
            assert($scope instanceof ClassDefinition);
432
433
            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...
434
                $definition = $scope->getExtendsClassDefinition();
435
                if ($definition) {
436
                    return new CompiledExpression(CompiledExpression::OBJECT, $definition);
437
                }
438
            } else {
439
                $this->context->notice(
440
                    'no-parent',
441
                    'Cannot access parent:: when current class scope has no parent',
442
                    $expr
443
                );
444
            }
445
        }
446
447 27
        if (in_array($nodeString, ['self', 'static'], true)) {
448 1
            return CompiledExpression::fromZvalValue($this->context->scope);
449
        }
450
451 26
        if (defined($nodeString)) {
452 7
            return CompiledExpression::fromZvalValue(constant($expr));
453
        }
454
455 23
        return new CompiledExpression(CompiledExpression::STRING, $expr->toString());
456
    }
457
458
    /**
459
     * @param Node\Expr\PropertyFetch $expr
460
     * @return CompiledExpression
461
     */
462
    protected function passPropertyFetch(Node\Expr\PropertyFetch $expr)
463
    {
464
        $propertNameCE = $this->compile($expr->name);
465
466
        $scopeExpression = $this->compile($expr->var);
467
        if ($scopeExpression->isObject()) {
468
            $scopeExpressionValue = $scopeExpression->getValue();
469
            if ($scopeExpressionValue instanceof ClassDefinition) {
470
                $propertyName = $propertNameCE->isString() ? $propertNameCE->getValue() : false;
471
                if ($propertyName) {
472
                    if ($scopeExpressionValue->hasProperty($propertyName, true)) {
473
                        $property = $scopeExpressionValue->getProperty($propertyName, true);
474
                        return $this->compile($property);
475
                    } else {
476
                        $this->context->notice(
477
                            'undefined-property',
478
                            sprintf(
479
                                'Property %s does not exist in %s scope',
480
                                $propertyName,
481
                                $scopeExpressionValue->getName()
482
                            ),
483
                            $expr
484
                        );
485
                    }
486
                }
487
            }
488
489
            return new CompiledExpression(CompiledExpression::UNKNOWN);
490
        } elseif ($scopeExpression->canBeObject()) {
491
            return new CompiledExpression(CompiledExpression::UNKNOWN);
492
        }
493
494
        $this->context->notice(
495
            'property-fetch-on-non-object',
496
            "It's not possible to fetch a property on a non-object",
497
            $expr,
498
            Check::CHECK_BETA
499
        );
500
501
        return new CompiledExpression(CompiledExpression::UNKNOWN);
502
    }
503
504
    /**
505
     * @param Node\Expr\Assign $expr
506
     * @return CompiledExpression
507
     */
508 29
    protected function passSymbol(Node\Expr\Assign $expr)
0 ignored issues
show
Complexity introduced by
This operation has 216 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...
509
    {
510 29
        $compiledExpression = $this->compile($expr->expr);
511
512 29
        if ($expr->var instanceof Node\Expr\List_) {
513 1
            $isCorrectType = $compiledExpression->isArray();
514
515 1
            foreach ($expr->var->vars as $key => $var) {
516 1
                if (!$var instanceof Node\Expr\Variable) {
517 1
                    continue;
518
                }
519
520 1
                if ($var->name instanceof Node\Expr\Variable) {
521 1
                    $this->compileVariableDeclaration($this->compile($var->name), new CompiledExpression());
522 1
                    continue;
523
                }
524
525 1
                $symbol = $this->context->getSymbol($var->name);
526 1
                if (!$symbol) {
527 1
                    $symbol = new Variable(
528 1
                        $var->name,
0 ignored issues
show
Bug introduced by
It seems like $var->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...
529 1
                        null,
530 1
                        CompiledExpression::UNKNOWN,
531 1
                        $this->context->getCurrentBranch()
532 1
                    );
533 1
                    $this->context->addVariable($symbol);
534 1
                }
535
536 1
                if (!$isCorrectType) {
537
                    $symbol->modify(CompiledExpression::NULL, null);
538
                }
539
540 1
                $symbol->incSets();
541 1
            }
542
543 1
            return new CompiledExpression();
544
        }
545
546 29
        if ($expr->var instanceof Node\Expr\Variable) {
547 29
            $this->compileVariableDeclaration($this->compile($expr->var->name), $compiledExpression);
548
549 29
            return $compiledExpression;
550
        }
551
552 2
        if ($expr->var instanceof Node\Expr\PropertyFetch) {
553 2
            $compiledExpression = $this->compile($expr->var->var);
554 2
            if ($compiledExpression->getType() == CompiledExpression::OBJECT) {
555 2
                $objectDefinition = $compiledExpression->getValue();
556 2
                if ($objectDefinition instanceof ClassDefinition) {
557 2
                    if (is_string($expr->var->name)) {
558 2
                        if ($objectDefinition->hasProperty($expr->var->name)) {
559
                            return $this->compile($objectDefinition->getProperty($expr->var->name));
560
                        }
561 2
                    }
562 2
                }
563 2
            }
564 2
        }
565
566 2
        $this->context->debug('Unknown how to pass symbol');
567 2
        return new CompiledExpression();
568
    }
569
570 29
    protected function compileVariableDeclaration(CompiledExpression $variableName, CompiledExpression $value)
571
    {
572 29
        switch ($variableName->getType()) {
573 29
            case CompiledExpression::STRING:
574 29
                break;
575
            default:
576
                $this->context->debug('Unexpected type of Variable name after compile');
577
                return new CompiledExpression();
578 29
        }
579
580 29
        $symbol = $this->context->getSymbol($variableName->getValue());
581 29
        if ($symbol) {
582 3
            $symbol->modify($value->getType(), $value->getValue());
583 3
            $this->context->modifyReferencedVariables(
584 3
                $symbol,
585 3
                $value->getType(),
586 3
                $value->getValue()
587 3
            );
588 3
        } else {
589 29
            $symbol = new Variable(
590 29
                $variableName->getValue(),
591 29
                $value->getValue(),
592 29
                $value->getType(),
593 29
                $this->context->getCurrentBranch()
594 29
            );
595 29
            $this->context->addVariable($symbol);
596
        }
597
598 29
        $symbol->incSets();
599 29
    }
600
601
    /**
602
     * @param Node\Expr\AssignRef $expr
603
     * @return CompiledExpression
604
     */
605 1
    protected function passSymbolByRef(Node\Expr\AssignRef $expr)
606
    {
607 1
        if ($expr->var instanceof Node\Expr\Variable) {
608 1
            $name = $expr->var->name;
609
610 1
            $compiledExpression = $this->compile($expr->expr);
611
612 1
            $symbol = $this->context->getSymbol($name);
613 1
            if ($symbol) {
614
                $symbol->modify($compiledExpression->getType(), $compiledExpression->getValue());
615
            } else {
616 1
                $symbol = new Variable(
617 1
                    $name,
0 ignored issues
show
Bug introduced by
It seems like $name defined by $expr->var->name on line 608 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...
618 1
                    $compiledExpression->getValue(),
619 1
                    $compiledExpression->getType(),
620 1
                    $this->context->getCurrentBranch()
621 1
                );
622 1
                $this->context->addVariable($symbol);
623
            }
624
625 1
            if ($expr->expr instanceof Node\Expr\Variable) {
626 1
                $rightVarName = $expr->expr->name;
627
628 1
                $rightSymbol = $this->context->getSymbol($rightVarName);
629 1
                if ($rightSymbol) {
630 1
                    $rightSymbol->incUse();
631 1
                    $symbol->setReferencedTo($rightSymbol);
632 1
                } else {
633
                    $this->context->debug('Cannot fetch variable by name: ' . $rightVarName);
634
                }
635 1
            }
636
637 1
            $symbol->incSets();
638 1
            return $compiledExpression;
639
        }
640
641
        $this->context->debug('Unknown how to pass symbol by ref');
642
        return new CompiledExpression();
643
    }
644
}
645