Skip to content

Commit

Permalink
[Rules] Skip valid return bool on ReturnNullOverFalseRule (#20)
Browse files Browse the repository at this point in the history
* tests: Add new test cases for the issue

* [Rules] Skip valid return bool on ReturnNullOverFalseRule

---------

Co-authored-by: Michael Telgmann <m.telgmann@shopware.com>
  • Loading branch information
samsonasik and mitelg authored Jun 18, 2024
1 parent 476f8ee commit df83404
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Rules/ReturnNullOverFalseRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PhpParser\NodeFinder;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Constant\ConstantBooleanType;
use Rector\TypePerfect\Configuration;

Expand Down Expand Up @@ -62,20 +63,32 @@ public function processNode(Node $node, Scope $scope): array
/** @var Return_[] $returns */
$returns = $this->nodeFinder->findInstanceOf($node->stmts, Return_::class);

$hasFalseType = false;
$hasTrueType = false;

foreach ($returns as $return) {
if (! $return->expr instanceof Expr) {
continue;
}

$exprType = $scope->getType($return->expr);
if (! $exprType instanceof ConstantBooleanType) {
if ($exprType instanceof BooleanType) {
return [];
}

continue;
}

if ($exprType->getValue()) {
$hasTrueType = true;
continue;
}

$hasFalseType = true;
}

if (! $hasTrueType && $hasFalseType) {
return [
self::ERROR_MESSAGE,
];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Rector\TypePerfect\Tests\Rules\ReturnNullOverFalseRule\Fixture;

class Loader
{
/**
* @return bool
*/
public function exists(string $name)
{
if (!$this->loadFromDb($name)) {
return false;
}

return true;
}

private function loadFromDb(string $name): ?array
{
if (mt_rand(1, 0)) {
return null;
}

return ['test' => 'foo'];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Rector\TypePerfect\Tests\Rules\ReturnNullOverFalseRule\Fixture;

class Entity
{
/**
* @param string $name
*
* @return bool
*/
public function __isset($name)
{
if (!$this->isPropertyVisible($name)) {
return false;
}

return isset($this->$name);
}

private function isPropertyVisible(string $name): bool
{
if (mt_rand(1, 0)) {
return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public static function provideData(): Iterator
__DIR__ . '/Fixture/ReturnFalseOnly.php',
[[ReturnNullOverFalseRule::ERROR_MESSAGE, 9]],
];
yield [__DIR__ . '/Fixture/CheckResultFromOtherMethod.php', []];
yield [__DIR__ . '/Fixture/CheckResultFromOtherMethod2.php', []];

yield [__DIR__ . '/Fixture/SkipReturnBool.php', []];
}
Expand Down

0 comments on commit df83404

Please sign in to comment.