Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -2152,6 +2152,10 @@ public function enterAnonymousFunctionWithoutReflection(
}
}

if ($this->shouldNotCarryForwardPropertyFetchInClosure($expr)) {
continue;
}

$expressionTypes[$exprString] = $typeHolder;
}

Expand Down Expand Up @@ -2218,6 +2222,28 @@ public function enterAnonymousFunctionWithoutReflection(
);
}

private function shouldNotCarryForwardPropertyFetchInClosure(Expr $expr): bool
{
if (!$expr instanceof PropertyFetch) {
return false;
}

if (!$expr->name instanceof Identifier) {
return false;
}

$objectType = $this->getType($expr->var);
$propertyName = $expr->name->name;

foreach ($objectType->getObjectClassReflections() as $classReflection) {
if ($classReflection->hasNativeProperty($propertyName)) {
return false;
}
}

return true;
}

private function expressionTypeIsUnchangeable(ExpressionTypeHolder $typeHolder): bool
{
$expr = $typeHolder->getExpr();
Expand Down
5 changes: 5 additions & 0 deletions tests/PHPStan/Rules/Arrays/DeadForeachRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,9 @@ public function testBug2457(): void
$this->analyse([__DIR__ . '/data/bug-2457.php'], []);
}

public function testBug10345(): void
{
$this->analyse([__DIR__ . '/data/bug-10345.php'], []);
}

}
15 changes: 15 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/bug-10345.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php declare(strict_types = 1);

namespace Bug10345;

$container = new \stdClass();
$container->items = [];

$func = function() use ($container): int {
foreach ($container->items as $item) {}
return 1;
};

$container->items[] = '1';

$a = $func();
Loading