Skip to content

Commit 1114ccc

Browse files
committed
Fix generic type inference for new assigned to property via ??=
- Added handling for AssignOp\Coalesce in NewAssignedToPropertyVisitor - The visitor now marks `new` expressions in `$this->prop ??= new Foo()` with the property attribute, so MutatingScope::exactInstantiation() can infer generic type parameters from the property's declared type - New regression test in tests/PHPStan/Rules/Properties/data/bug-12250.php Closes phpstan/phpstan#12250
1 parent 106fc93 commit 1114ccc

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

src/Parser/NewAssignedToPropertyVisitor.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ final class NewAssignedToPropertyVisitor extends NodeVisitorAbstract
1616
#[Override]
1717
public function enterNode(Node $node): ?Node
1818
{
19-
if ($node instanceof Node\Expr\Assign || $node instanceof Node\Expr\AssignRef) {
19+
if ($node instanceof Node\Expr\Assign || $node instanceof Node\Expr\AssignRef || $node instanceof Node\Expr\AssignOp\Coalesce) {
2020
if (
2121
($node->var instanceof Node\Expr\PropertyFetch || $node->var instanceof Node\Expr\StaticPropertyFetch)
2222
&& $node->expr instanceof Node\Expr\New_

tests/PHPStan/Rules/Properties/TypesAssignedToPropertiesRuleTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,4 +1003,10 @@ public function testCloneWith(): void
10031003
]);
10041004
}
10051005

1006+
#[RequiresPhp('>= 8.0')]
1007+
public function testBug12250(): void
1008+
{
1009+
$this->analyse([__DIR__ . '/data/bug-12250.php'], []);
1010+
}
1011+
10061012
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php // lint >= 8.0
2+
3+
namespace Bug12250;
4+
5+
class HelloWorld
6+
{
7+
/**
8+
* @var \WeakMap<\stdClass, \stdClass>
9+
*/
10+
protected \WeakMap $bug, $ok;
11+
12+
public function bug(): void
13+
{
14+
$this->bug ??= new \WeakMap();
15+
$this->ok = new \WeakMap();
16+
}
17+
}

0 commit comments

Comments
 (0)