diff --git a/CHANGELOG.md b/CHANGELOG.md index fc8557c8..b461c757 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ For a full diff see [`2.5.0...main`][2.5.0...main]. - Returned rule with error identifier ([#882]), by [@localheinz] - Adjusted `Methods\FinalInAbstractClassRule` to ignore Doctrine embeddables and entities ([#396]), by [@localheinz] - Adjusted `Expressions\NoCompactRule` to detect usages of `compact()` with incorrect case ([#889]), by [@localheinz] +- Adjusted `Methods\PrivateInFinalClass` to use more appropriate message when detecting a `proected` method in an anonymous class ([#890]), by [@localheinz] ## [`2.5.0`][2.5.0] @@ -552,6 +553,7 @@ For a full diff see [`362c7ea...0.1.0`][362c7ea...0.1.0]. [#880]: https://github.com/ergebnis/phpstan-rules/pull/880 [#882]: https://github.com/ergebnis/phpstan-rules/pull/882 [#889]: https://github.com/ergebnis/phpstan-rules/pull/889 +[#890]: https://github.com/ergebnis/phpstan-rules/pull/890 [@enumag]: https://github.com/enumag [@ergebnis]: https://github.com/ergebnis diff --git a/src/Methods/PrivateInFinalClassRule.php b/src/Methods/PrivateInFinalClassRule.php index 4c6ce4d7..ec1f5062 100644 --- a/src/Methods/PrivateInFinalClassRule.php +++ b/src/Methods/PrivateInFinalClassRule.php @@ -60,6 +60,22 @@ public function processNode( } } + /** @var Reflection\ClassReflection $classReflection */ + $classReflection = $scope->getClassReflection(); + + if ($classReflection->isAnonymous()) { + $message = \sprintf( + 'Method %s() in anonymous class is protected, but since the containing class is final, it can be private.', + $node->name->name, + ); + + return [ + Rules\RuleErrorBuilder::message($message) + ->identifier(ErrorIdentifier::privateInFinalClass()->toString()) + ->build(), + ]; + } + $message = \sprintf( 'Method %s::%s() is protected, but since the containing class is final, it can be private.', $containingClass->getName(), diff --git a/test/Integration/Methods/PrivateInFinalClassRuleTest.php b/test/Integration/Methods/PrivateInFinalClassRuleTest.php index ec0d4d40..41436b14 100644 --- a/test/Integration/Methods/PrivateInFinalClassRuleTest.php +++ b/test/Integration/Methods/PrivateInFinalClassRuleTest.php @@ -47,6 +47,13 @@ public static function provideCasesWhereAnalysisShouldSucceed(): iterable public static function provideCasesWhereAnalysisShouldFail(): iterable { $paths = [ + 'anonymous-class-with-protected-method' => [ + __DIR__ . '/../../Fixture/Methods/PrivateInFinalClassRule/Failure/AnonymousClassWithProtectedMethod.php', + [ + 'Method method() in anonymous class is protected, but since the containing class is final, it can be private.', + 8, + ], + ], 'final-class-with-protected-method' => [ __DIR__ . '/../../Fixture/Methods/PrivateInFinalClassRule/Failure/FinalClassWithProtectedMethod.php', [