Skip to content

Commit

Permalink
Include property intializations from parent scope for anonymous funct…
Browse files Browse the repository at this point in the history
…ions
  • Loading branch information
fabacino authored Oct 13, 2023
1 parent 66d7e5e commit 6891738
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Node/ClassPropertiesNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,14 +218,17 @@ public function getUninitializedProperties(
}
}
} elseif (array_key_exists($propertyName, $initializedPropertiesMap)) {
$hasInitialization = $initializedPropertiesMap[$propertyName]->or($usageScope->hasExpressionType(new PropertyInitializationExpr($propertyName)));
if (
strtolower($function->getName()) !== '__construct'
&& array_key_exists($propertyName, $initializedInConstructor)
&& in_array($function->getName(), $constructors, true)
) {
continue;
}
$hasInitialization = $initializedPropertiesMap[$propertyName]->or($usageScope->hasExpressionType(new PropertyInitializationExpr($propertyName)));
if (!$hasInitialization->yes() && $usageScope->isInAnonymousFunction() && $usageScope->getParentScope() !== null) {
$hasInitialization = $hasInitialization->or($usageScope->getParentScope()->hasExpressionType(new PropertyInitializationExpr($propertyName)));
}
if (!$hasInitialization->yes()) {
$prematureAccess[] = [
$propertyName,
Expand Down
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/Properties/UninitializedPropertyRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,4 +192,14 @@ public function testBug9619(): void
]);
}

public function testBug9831(): void
{
$this->analyse([__DIR__ . '/data/bug-9831.php'], [
[
'Access to an uninitialized property Bug9831\Foo::$bar.',
12,
],
]);
}

}
21 changes: 21 additions & 0 deletions tests/PHPStan/Rules/Properties/data/bug-9831.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php // lint >= 8.1

namespace Bug9831;

class Foo
{
private string $bar;

public function __construct()
{
$var = function (): void {
echo $this->bar;
};

$this->bar = '123';

$var = function (): void {
echo $this->bar;
};
}
}

0 comments on commit 6891738

Please sign in to comment.