Search code examples
phplaravelif-statementphpmd

how should remove else blocks


PHPMD is telling me that I should avoid else block in this test, but in those case, I can't find a way to remove them.

Here is the code:

if ($fight->c1 == NULL) {
    if ($fight->c2 == NULL) {
        // C1 and C2 Is Bye
        $this->assertEquals($parentFight->$toUpdate, NULL);
    }
    else {
        // C1 Is Bye
        $this->assertEquals($parentFight->$toUpdate, $fight->c2);
    }
}
else {
    if ($fight->c2 == NULL) {
        // C2 Is Bye
        $this->assertEquals($parentFight->$toUpdate, $fight->c1);
    }
    else {
        // C1 and C2 Are all set
        $this->assertEquals($parentFight->$toUpdate, NULL);
    }
}

Any Idea???


Solution

  • It could also be done with a ternary operator, something like this.

    if (!$fight->c1) {
        $this->assertEquals($parentFight->$toUpdate, ($fight->c2 ?: null));
    }
    
    if (!$fight->c2) {
        $this->assertEquals($parentFight->$toUpdate, ($fight->c2 ?: null));
    }