Skip to content

Commit bc8279f

Browse files
committed
Generic/UselessOverridingMethod: bail if not checking a class method
The UselessOverridingMethod is triggered when the T_FUNCTION token is found. This token is used for regular functions and also methods. The sniff should run only for class methods (including abstract and anonymous classes). Those are the only methods that can have a parent. So this commit changes the sniff to bail early when dealing with a regular function or a trait, interface or enum method.
1 parent ff00744 commit bc8279f

File tree

4 files changed

+48
-5
lines changed

4 files changed

+48
-5
lines changed

src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php

+5
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ public function process(File $phpcsFile, $stackPtr)
6060
return;
6161
}
6262

63+
// Skip functions and also trait, interface and enum methods.
64+
if ($phpcsFile->hasCondition($stackPtr, [T_CLASS, T_ANON_CLASS]) === false) {
65+
return;
66+
}
67+
6368
// Get function name.
6469
$methodName = $phpcsFile->getDeclarationName($stackPtr);
6570

src/Standards/Generic/Tests/CodeAnalysis/UselessOverridingMethodUnitTest.1.inc

+28
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,31 @@ interface InterfaceFoo {
8181
trait TraitFoo {
8282
abstract public function sniffShouldBailEarly();
8383
}
84+
85+
abstract class AbstractBar extends AbstractFoo {
86+
public function uselessMethodInAbstractClass() {
87+
parent::uselessMethodInAbstractClass();
88+
}
89+
90+
public function usefulMethodInAbstractClass() {
91+
$a = 1;
92+
parent::usefulMethodInAbstractClass($a);
93+
}
94+
}
95+
96+
enum EnumFoo {
97+
public function sniffShouldBailEarly() {}
98+
}
99+
100+
new class extends ParentClass {
101+
public function __construct() {
102+
parent::__construct();
103+
}
104+
};
105+
106+
new class extends ParentClass {
107+
public function __construct() {
108+
$a = 10;
109+
parent::__construct($a);
110+
}
111+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
// Intentional fatal error (calling parent inside a function).
4+
// Testing that the sniff is *not* triggered in this case.
5+
6+
function __construct() {
7+
parent::__construct();
8+
}

src/Standards/Generic/Tests/CodeAnalysis/UselessOverridingMethodUnitTest.php

+7-5
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,13 @@ public function getWarningList($testFile='')
5050
switch ($testFile) {
5151
case 'UselessOverridingMethodUnitTest.1.inc':
5252
return [
53-
4 => 1,
54-
16 => 1,
55-
38 => 1,
56-
56 => 1,
57-
68 => 1,
53+
4 => 1,
54+
16 => 1,
55+
38 => 1,
56+
56 => 1,
57+
68 => 1,
58+
86 => 1,
59+
101 => 1,
5860
];
5961
default:
6062
return [];

0 commit comments

Comments
 (0)