Skip to content

Commit 7232c17

Browse files
VincentLangletondrejmirtes
authored andcommitted
Add rule for countable
1 parent a3aeb34 commit 7232c17

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

src/Rules/PHPUnit/AssertSameWithCountRule.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PhpParser\Node;
66
use PHPStan\Analyser\Scope;
7+
use PHPStan\Type\ObjectType;
78

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

48+
if (
49+
$right instanceof Node\Expr\MethodCall
50+
&& $right->name instanceof Node\Identifier
51+
&& strtolower($right->name->toString()) === 'count'
52+
&& count($right->args) === 0
53+
) {
54+
$type = $scope->getType($right->var);
55+
56+
if ((new ObjectType(\Countable::class))->isSuperTypeOf($type)->yes()) {
57+
return [
58+
'You should use assertCount($expectedCount, $variable) instead of assertSame($expectedCount, $variable->count()).',
59+
];
60+
}
61+
}
62+
4763
return [];
4864
}
4965

tests/Rules/PHPUnit/AssertSameWithCountRuleTest.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,11 @@ public function testRule(): void
2424
],
2525
[
2626
'You should use assertCount($expectedCount, $variable) instead of assertSame($expectedCount, count($variable)).',
27-
20,
27+
22,
28+
],
29+
[
30+
'You should use assertCount($expectedCount, $variable) instead of assertSame($expectedCount, $variable->count()).',
31+
30,
2832
],
2933
]);
3034
}

tests/Rules/PHPUnit/data/assert-same-count.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,29 @@ public function testAssertSameWithCount()
1212

1313
public function testAssertSameWithCountMethodIsOK()
1414
{
15-
$this->assertSame(5, $this->count()); // OK
15+
$foo = new \stdClass();
16+
17+
$this->assertSame(5, $foo->count()); // OK
1618
}
1719

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

25+
public function testAssertSameWithCountMethodForCountableVariableIsNotOK()
26+
{
27+
$foo = new \stdClass();
28+
$foo->bar = new Bar ();
29+
30+
$this->assertSame(5, $foo->bar->count());
31+
}
32+
2333
}
34+
35+
class Bar implements \Countable {
36+
public function count()
37+
{
38+
return 1;
39+
}
40+
};

0 commit comments

Comments
 (0)