File tree Expand file tree Collapse file tree 2 files changed +38
-1
lines changed
tests/Rule/data/ForbidUselessNullableReturnRule Expand file tree Collapse file tree 2 files changed +38
-1
lines changed Original file line number Diff line number Diff line change 66use PHPStan \Analyser \Scope ;
77use PHPStan \Node \ClosureReturnStatementsNode ;
88use PHPStan \Node \ReturnStatementsNode ;
9+ use PHPStan \Reflection \MethodReflection ;
910use PHPStan \Rules \IdentifierRuleError ;
1011use PHPStan \Rules \Rule ;
1112use PHPStan \Rules \RuleErrorBuilder ;
@@ -38,6 +39,10 @@ public function processNode(
3839 $ verbosity = VerbosityLevel::precise ();
3940 $ methodReflection = $ scope ->getFunction ();
4041
42+ if ($ methodReflection instanceof MethodReflection && $ this ->isOverridable ($ methodReflection )) {
43+ return [];
44+ }
45+
4146 if ($ node instanceof ClosureReturnStatementsNode) {
4247 $ declaredType = $ scope ->getFunctionType ($ node ->getClosureExpr ()->getReturnType (), false , false );
4348 } elseif ($ methodReflection !== null ) {
@@ -80,4 +85,9 @@ public function processNode(
8085 return [];
8186 }
8287
88+ private function isOverridable (MethodReflection $ methodReflection ): bool
89+ {
90+ return !$ methodReflection ->isFinal ()->yes () && !$ methodReflection ->isPrivate () && !$ methodReflection ->isStatic () && !$ methodReflection ->getDeclaringClass ()->isFinalByKeyword ();
91+ }
92+
8393}
Original file line number Diff line number Diff line change 22
33namespace ForbidUselessNullableReturnRule ;
44
5- class ExampleClass {
5+ final class ExampleClass {
66
77 private ?int $ foo ;
88
@@ -87,3 +87,30 @@ function nullableFunction(int $int): ?int // error: Declared return type int|nul
8787$ globalFn = static function (int $ int ): ?int { // error: Declared return type int|null contains null, but it is never returned. Returned types: int.
8888 return $ int ;
8989};
90+
91+ class NonFinalClass {
92+ public static function staticMethod (): ?int // error: Declared return type int|null contains null, but it is never returned. Returned types: 1.
93+ {
94+ return 1 ;
95+ }
96+
97+ final public function finalMethod (): ?int // error: Declared return type int|null contains null, but it is never returned. Returned types: 1.
98+ {
99+ return 1 ;
100+ }
101+
102+ private function privateMethod (): ?int // error: Declared return type int|null contains null, but it is never returned. Returned types: 1.
103+ {
104+ return 1 ;
105+ }
106+
107+ public function publicMethod (): ?int
108+ {
109+ return 1 ;
110+ }
111+
112+ protected function protectedMethod (): ?int
113+ {
114+ return 1 ;
115+ }
116+ }
You can’t perform that action at this time.
0 commit comments