From b116d25a6e4ba6c09f59af6569d9e6f6fd20aff4 Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Tue, 16 Apr 2024 17:47:00 +0200 Subject: [PATCH] CallToConstructorStatementWithoutSideEffectsRule - report class with no constructor --- ...lToConstructorStatementWithoutSideEffectsRule.php | 7 ++++++- ...onstructorStatementWithoutSideEffectsRuleTest.php | 12 ++++++++++++ .../data/constructor-statement-no-side-effects.php | 9 +++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRule.php b/src/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRule.php index 4dec25393..a3fa8e0a3 100644 --- a/src/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRule.php +++ b/src/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRule.php @@ -43,7 +43,12 @@ public function processNode(Node $node, Scope $scope): array $classReflection = $this->reflectionProvider->getClass($className); if (!$classReflection->hasConstructor()) { - return []; + return [ + RuleErrorBuilder::message(sprintf( + 'Call to new %s() on a separate line has no effect.', + $classReflection->getDisplayName(), + ))->identifier('new.resultUnused')->build(), + ]; } $constructor = $classReflection->getConstructor(); diff --git a/tests/PHPStan/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRuleTest.php b/tests/PHPStan/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRuleTest.php index 917cc77f8..c7c0e8f89 100644 --- a/tests/PHPStan/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRuleTest.php +++ b/tests/PHPStan/Rules/Methods/CallToConstructorStatementWithoutSideEffectsRuleTest.php @@ -23,6 +23,14 @@ public function testRule(): void 'Call to Exception::__construct() on a separate line has no effect.', 6, ], + [ + 'Call to new PDOStatement() on a separate line has no effect.', + 11, + ], + [ + 'Call to new stdClass() on a separate line has no effect.', + 12, + ], [ 'Call to ConstructorStatementNoSideEffects\ConstructorWithPure::__construct() on a separate line has no effect.', 57, @@ -31,6 +39,10 @@ public function testRule(): void 'Call to ConstructorStatementNoSideEffects\ConstructorWithPureAndThrowsVoid::__construct() on a separate line has no effect.', 58, ], + [ + 'Call to new ConstructorStatementNoSideEffects\NoConstructor() on a separate line has no effect.', + 68, + ], ]); } diff --git a/tests/PHPStan/Rules/Methods/data/constructor-statement-no-side-effects.php b/tests/PHPStan/Rules/Methods/data/constructor-statement-no-side-effects.php index 5b8219062..02f109f3c 100644 --- a/tests/PHPStan/Rules/Methods/data/constructor-statement-no-side-effects.php +++ b/tests/PHPStan/Rules/Methods/data/constructor-statement-no-side-effects.php @@ -58,3 +58,12 @@ function(): void { new ConstructorWithPureAndThrowsVoid(); new ConstructorWithPureAndThrowsException(); }; + +class NoConstructor +{ + +} + +function (): void { + new NoConstructor(); +};