Skip to content

Commit 9a2a033

Browse files
authored
EnforceNativeReturnTypehintRule: fix property hook false positive (#309)
1 parent 603c013 commit 9a2a033

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

src/Rule/EnforceNativeReturnTypehintRule.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PhpParser\Node\Expr\Throw_;
88
use PhpParser\Node\Stmt\Expression;
99
use PHPStan\Analyser\Scope;
10+
use PHPStan\Node\PropertyHookReturnStatementsNode;
1011
use PHPStan\Node\ReturnStatementsNode;
1112
use PHPStan\Php\PhpVersion;
1213
use PHPStan\Rules\IdentifierRuleError;
@@ -80,6 +81,10 @@ public function processNode(
8081
return [];
8182
}
8283

84+
if ($node instanceof PropertyHookReturnStatementsNode) {
85+
return []; // hooks cannot have native return typehints
86+
}
87+
8388
if (!$scope->isInAnonymousFunction() && in_array($scope->getFunctionName(), ['__construct', '__destruct', '__clone'], true)) {
8489
return [];
8590
}

tests/Rule/EnforceNativeReturnTypehintRuleTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,16 @@ public function testEnum(): void
3737
$this->analyseFile(__DIR__ . '/data/EnforceNativeReturnTypehintRule/code-enum.php');
3838
}
3939

40+
public function testHooks(): void
41+
{
42+
if (PHP_VERSION_ID < 80_400) {
43+
self::markTestSkipped('Requires PHP 8.4');
44+
}
45+
46+
$this->phpVersion = self::getContainer()->getByType(PhpVersion::class);
47+
$this->analyseFile(__DIR__ . '/data/EnforceNativeReturnTypehintRule/code-hook.php');
48+
}
49+
4050
public function testPhp82(): void
4151
{
4252
$this->phpVersion = $this->createPhpVersion(80_200);
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace EnforceNativeReturnTypehintRuleHooks;
4+
5+
class Person
6+
{
7+
public int $age = 0 {
8+
set => $value >= 0 ? $value : throw new InvalidArgumentException;
9+
}
10+
11+
}

0 commit comments

Comments
 (0)