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

Ternary::compile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
nc 2
nop 2
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 2
rs 9.4285
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 Ternary extends AbstractExpressionCompiler
11
{
12
    protected $name = 'PhpParser\Node\Expr\Ternary';
13
14
    /**
15
     * ({expr}) ? {expr} : {expr}
16
     *
17
     * @param \PhpParser\Node\Expr\Ternary $expr
18
     * @param Context $context
19
     * @return CompiledExpression
20
     */
21 2
    protected function compile($expr, Context $context)
22
    {
23 2
        $condition = $context->getExpressionCompiler()->compile($expr->cond);
24 2
        $left = $context->getExpressionCompiler()->compile($expr->if);
0 ignored issues
show
Bug introduced by
It seems like $expr->if 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...
25 2
        $right = $context->getExpressionCompiler()->compile($expr->else);
26
27 2
        if ($condition->getValue() == true) {
28 1
            return CompiledExpression::fromZvalValue($left->getValue());
29
        } else {
30 1
            return CompiledExpression::fromZvalValue($right->getValue());
31
        }
32
    }
33
}
34