Completed
Pull Request — master (#290)
by Enrico
03:35
created

ReturnSt::compile()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 2
dl 0
loc 19
ccs 12
cts 12
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Patsura Dmitry https://github.com/ovr <[email protected]>
4
 */
5
6
namespace PHPSA\Compiler\Statement;
7
8
use PHPSA\CompiledExpression;
9
use PHPSA\Context;
10
use PHPSA\Definition\ClassMethod;
11
12
class ReturnSt extends AbstractCompiler
13
{
14
    protected $name = '\PhpParser\Node\Stmt\Return_';
15
16
    /**
17
     * @param \PhpParser\Node\Stmt\Return_ $stmt
18
     * @param Context $context
19
     * @return CompiledExpression
20
     */
21 34
    public function compile($stmt, Context $context)
22
    {
23 34
        $compiledExpression = $context->getExpressionCompiler()->compile($stmt->expr);
0 ignored issues
show
Bug introduced by
It seems like $stmt->expr 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...
24
25 34
        if ($context->scopePointer) {
26
            /**
27
             * If it is a Class's method we need to work on return types, return possible values
28
             */
29 34
            if ($context->scopePointer->isClassMethod()) {
30
                /** @var ClassMethod $classMethod */
31 34
                $classMethod = $context->scopePointer->getObject();
32 34
                $classMethod->addNewType($compiledExpression->getType());
33
34 34
                if ($compiledExpression->isCorrectValue()) {
35 34
                    $classMethod->addReturnPossibleValue($compiledExpression->getValue());
36 34
                }
37 34
            }
38 34
        }
39 34
    }
40
}
41