Skip to content

Commit d98b140

Browse files
phpstan-botclaude
andcommitted
Use catch type as assigned expression in VariableAssignNode for catch variables
The VariableAssignNode for catch variables was using the variable itself as the assigned expression, which meant ParameterOutAssignedTypeRule could not detect type mismatches when a catch variable overwrites a by-ref parameter. Now uses TypeExpr wrapping the catch type so the parameterByRef.type check works correctly. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 398df87 commit d98b140

3 files changed

Lines changed: 38 additions & 1 deletion

File tree

src/Analyser/NodeScopeResolver.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1974,7 +1974,7 @@ public function processStmtNode(
19741974
}
19751975

19761976
$variableName = $catchNode->var->name;
1977-
$this->callNodeCallback($nodeCallback, new VariableAssignNode($catchNode->var, $catchNode->var), $scope, $storage);
1977+
$this->callNodeCallback($nodeCallback, new VariableAssignNode($catchNode->var, new TypeExpr($catchType)), $scope, $storage);
19781978
}
19791979

19801980
$catchScopeResult = $this->processStmtNodesInternal($catchNode, $catchNode->stmts, $catchScope->enterCatchType($catchType, $variableName), $storage, $nodeCallback, $context);

tests/PHPStan/Rules/Variables/ParameterOutAssignedTypeRuleTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,19 @@ public function testBug14124b(): void
9191
$this->analyse([__DIR__ . '/data/bug-14124b.php'], []);
9292
}
9393

94+
public function testCatchVariable(): void
95+
{
96+
$this->analyse([__DIR__ . '/data/parameter-out-catch-variable.php'], [
97+
[
98+
'Parameter &$p @param-out type of function ParameterOutCatchVariable\foo() expects int, Exception given.',
99+
11,
100+
],
101+
[
102+
'Parameter &$p by-ref type of function ParameterOutCatchVariable\bar() expects int, Exception given.',
103+
19,
104+
'You can change the parameter out type with @param-out PHPDoc tag.',
105+
],
106+
]);
107+
}
108+
94109
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
namespace ParameterOutCatchVariable;
4+
5+
/**
6+
* @param-out int $p
7+
*/
8+
function foo(&$p): void {
9+
try {
10+
throw new \Exception();
11+
} catch (\Exception $p) {
12+
13+
}
14+
}
15+
16+
function bar(int &$p): void {
17+
try {
18+
throw new \Exception();
19+
} catch (\Exception $p) {
20+
21+
}
22+
}

0 commit comments

Comments
 (0)