Completed
Pull Request — master (#149)
by Enrico
04:04
created

Expression::passExprVariable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

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