Skip to content

Commit d736f4e

Browse files
paulbalandanondrejmirtes
authored andcommitted
Detect non-abstract methods with no body
1 parent 993413f commit d736f4e

File tree

3 files changed

+36
-8
lines changed

3 files changed

+36
-8
lines changed

src/Rules/Methods/AbstractMethodInNonAbstractClassRule.php

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,29 @@ public function processNode(Node $node, Scope $scope): array
2727
}
2828

2929
$class = $scope->getClassReflection();
30-
if ($class->isAbstract()) {
31-
return [];
30+
31+
if (!$class->isAbstract() && $node->isAbstract()) {
32+
return [
33+
RuleErrorBuilder::message(sprintf(
34+
'%s %s contains abstract method %s().',
35+
$class->isInterface() ? 'Interface' : 'Non-abstract class',
36+
$class->getDisplayName(),
37+
$node->name->toString(),
38+
))->nonIgnorable()->build(),
39+
];
3240
}
3341

34-
if (!$node->isAbstract()) {
35-
return [];
42+
if (!$class->isAbstract() && !$class->isInterface() && $node->getStmts() === null) {
43+
return [
44+
RuleErrorBuilder::message(sprintf(
45+
'Non-abstract method %s::%s() must contain a body.',
46+
$class->getDisplayName(),
47+
$node->name->toString(),
48+
))->nonIgnorable()->build(),
49+
];
3650
}
3751

38-
return [
39-
RuleErrorBuilder::message(sprintf('Non-abstract class %s contains abstract method %s().', $class->getDisplayName(), $node->name->toString()))->nonIgnorable()->build(),
40-
];
52+
return [];
4153
}
4254

4355
}

tests/PHPStan/Rules/Methods/AbstractMethodInNonAbstractClassRuleTest.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public function testRule(): void
2626
15,
2727
],
2828
[
29-
'Non-abstract class AbstractMethod\Baz contains abstract method doBar().',
29+
'Interface AbstractMethod\Baz contains abstract method doBar().',
3030
22,
3131
],
3232
]);
@@ -60,4 +60,14 @@ public function testBug4214(): void
6060
$this->analyse([__DIR__ . '/data/bug-4214.php'], []);
6161
}
6262

63+
public function testNonAbstractMethodWithNoBody(): void
64+
{
65+
$this->analyse([__DIR__ . '/data/bug-4244.php'], [
66+
[
67+
'Non-abstract method HelloWorld::sayHello() must contain a body.',
68+
5,
69+
],
70+
]);
71+
}
72+
6373
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php declare(strict_types = 1);
2+
3+
class HelloWorld
4+
{
5+
public function sayHello(): void;
6+
}

0 commit comments

Comments
 (0)