Completed
Pull Request — master (#196)
by Enrico
05:34 queued 41s
created

ArrayDimFetch::compile()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 18
nc 3
nop 2
dl 0
loc 31
ccs 0
cts 18
cp 0
crap 20
rs 8.5806
c 1
b 0
f 0
1
<?php
2
3
namespace PHPSA\Compiler\Expression;
4
5
use PHPSA\CompiledExpression;
6
use PHPSA\Context;
7
use PHPSA\Compiler\Expression;
8
use PHPSA\Compiler\Expression\AbstractExpressionCompiler;
9
10
class ArrayDimFetch extends AbstractExpressionCompiler
11
{
12
    protected $name = 'PhpParser\Node\Expr\ArrayDimFetch';
13
14
    /**
15
     * $array[1], $array[$var], $array["string"]
16
     *
17
     * @param \PhpParser\Node\Expr\ArrayDimFetch $expr
18
     * @param Context $context
19
     * @return CompiledExpression
20
     */
21
    protected function compile($expr, Context $context)
22
    {
23
        $compiler = $context->getExpressionCompiler();
24
25
        $var = $compiler->compile($expr->var);
26
        $dim = $compiler->compile($expr->dim);
0 ignored issues
show
Bug introduced by
It seems like $expr->dim can be null; however, compile() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
27
28
        if (!$var->isArray() && !$var->getType() == CompiledExpression::MIXED) {
29
            $context->notice(
30
                'array_dim_fetch_on_non_array',
31
                "It's not possible to fetch an array element on a non array",
32
                $expr
33
            );
34
            
35
            return new CompiledExpression();
36
        }
37
38
        if (!in_array($dim->getValue(), $var->getValue())) {
39
            $context->notice(
40
                'array_dim_fetch_not_found',
41
                "The array does not contain this value",
42
                $expr
43
            );
44
45
            return new CompiledExpression();
46
        }
47
48
        $resultArray = $var->getValue();
49
50
        return CompiledExpression::fromZvalValue($resultArray[$dim->getValue()]);
51
    }
52
}
53