diff --git a/src/Rule/EnforceNativeReturnTypehintRule.php b/src/Rule/EnforceNativeReturnTypehintRule.php index c573b60..da463de 100644 --- a/src/Rule/EnforceNativeReturnTypehintRule.php +++ b/src/Rule/EnforceNativeReturnTypehintRule.php @@ -7,6 +7,7 @@ use PhpParser\Node\Expr\Throw_; use PhpParser\Node\Stmt\Expression; use PHPStan\Analyser\Scope; +use PHPStan\Node\PropertyHookReturnStatementsNode; use PHPStan\Node\ReturnStatementsNode; use PHPStan\Php\PhpVersion; use PHPStan\Rules\IdentifierRuleError; @@ -80,6 +81,10 @@ public function processNode( return []; } + if ($node instanceof PropertyHookReturnStatementsNode) { + return []; // hooks cannot have native return typehints + } + if (!$scope->isInAnonymousFunction() && in_array($scope->getFunctionName(), ['__construct', '__destruct', '__clone'], true)) { return []; } diff --git a/tests/Rule/EnforceNativeReturnTypehintRuleTest.php b/tests/Rule/EnforceNativeReturnTypehintRuleTest.php index 14d00ae..4b43a8a 100644 --- a/tests/Rule/EnforceNativeReturnTypehintRuleTest.php +++ b/tests/Rule/EnforceNativeReturnTypehintRuleTest.php @@ -37,6 +37,16 @@ public function testEnum(): void $this->analyseFile(__DIR__ . '/data/EnforceNativeReturnTypehintRule/code-enum.php'); } + public function testHooks(): void + { + if (PHP_VERSION_ID < 80_400) { + self::markTestSkipped('Requires PHP 8.4'); + } + + $this->phpVersion = self::getContainer()->getByType(PhpVersion::class); + $this->analyseFile(__DIR__ . '/data/EnforceNativeReturnTypehintRule/code-hook.php'); + } + public function testPhp82(): void { $this->phpVersion = $this->createPhpVersion(80_200); diff --git a/tests/Rule/data/EnforceNativeReturnTypehintRule/code-hook.php b/tests/Rule/data/EnforceNativeReturnTypehintRule/code-hook.php new file mode 100644 index 0000000..9883964 --- /dev/null +++ b/tests/Rule/data/EnforceNativeReturnTypehintRule/code-hook.php @@ -0,0 +1,11 @@ + $value >= 0 ? $value : throw new InvalidArgumentException; + } + +}