Completed
Pull Request — master (#196)
by Enrico
05:42
created

ArrayDimFetch   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 43
ccs 0
cts 18
cp 0
rs 10
wmc 3
lcom 0
cbo 5

1 Method

Rating   Name   Duplication   Size   Complexity  
B compile() 0 31 3
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()) {
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