Skip to content

Commit

Permalink
Add rule for countable
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet authored and ondrejmirtes committed Apr 17, 2020
1 parent a3aeb34 commit 7232c17
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
16 changes: 16 additions & 0 deletions src/Rules/PHPUnit/AssertSameWithCountRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Type\ObjectType;

/**
* @implements \PHPStan\Rules\Rule<\PhpParser\NodeAbstract>
Expand Down Expand Up @@ -44,6 +45,21 @@ public function processNode(Node $node, Scope $scope): array
];
}

if (
$right instanceof Node\Expr\MethodCall
&& $right->name instanceof Node\Identifier
&& strtolower($right->name->toString()) === 'count'
&& count($right->args) === 0
) {
$type = $scope->getType($right->var);

if ((new ObjectType(\Countable::class))->isSuperTypeOf($type)->yes()) {
return [
'You should use assertCount($expectedCount, $variable) instead of assertSame($expectedCount, $variable->count()).',
];
}
}

return [];
}

Expand Down
6 changes: 5 additions & 1 deletion tests/Rules/PHPUnit/AssertSameWithCountRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ public function testRule(): void
],
[
'You should use assertCount($expectedCount, $variable) instead of assertSame($expectedCount, count($variable)).',
20,
22,
],
[
'You should use assertCount($expectedCount, $variable) instead of assertSame($expectedCount, $variable->count()).',
30,
],
]);
}
Expand Down
19 changes: 18 additions & 1 deletion tests/Rules/PHPUnit/data/assert-same-count.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,29 @@ public function testAssertSameWithCount()

public function testAssertSameWithCountMethodIsOK()
{
$this->assertSame(5, $this->count()); // OK
$foo = new \stdClass();

$this->assertSame(5, $foo->count()); // OK
}

public function testAssertSameIsDetectedWithDirectAssertAccess()
{
\PHPUnit\Framework\Assert::assertSame(5, count([1, 2, 3]));
}

public function testAssertSameWithCountMethodForCountableVariableIsNotOK()
{
$foo = new \stdClass();
$foo->bar = new Bar ();

$this->assertSame(5, $foo->bar->count());
}

}

class Bar implements \Countable {
public function count()
{
return 1;
}
};

0 comments on commit 7232c17

Please sign in to comment.