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
15 changes: 15 additions & 0 deletions src/Analyser/SpecifiedTypes.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,21 @@ public function getRootExpr(): ?Expr
return $this->rootExpr;
}

public function removeExpr(string $exprString): self
{
$sureTypes = $this->sureTypes;
$sureNotTypes = $this->sureNotTypes;
unset($sureTypes[$exprString]);
unset($sureNotTypes[$exprString]);

$self = new self($sureTypes, $sureNotTypes);
$self->overwrite = $this->overwrite;
$self->newConditionalExpressionHolders = $this->newConditionalExpressionHolders;
$self->rootExpr = $this->rootExpr;

return $self;
}

/** @api */
public function intersectWith(SpecifiedTypes $other): self
{
Expand Down
3 changes: 3 additions & 0 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,9 @@ public function specifyTypesInCondition(

if ($context->null()) {
$specifiedTypes = $this->specifyTypesInCondition($scope->exitFirstLevelStatements(), $expr->expr, $context)->setRootExpr($expr);
if ($expr->var instanceof Expr\Variable && is_string($expr->var->name)) {
$specifiedTypes = $specifiedTypes->removeExpr('$' . $expr->var->name);
}
} else {
$specifiedTypes = $this->specifyTypesInCondition($scope->exitFirstLevelStatements(), $expr->var, $context)->setRootExpr($expr);
}
Expand Down
36 changes: 36 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-11565.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php declare(strict_types = 1);

namespace Bug11565;

use function PHPStan\Testing\assertType;

/**
* @template T
* @param iterable<mixed, T> $iterable
* @return ($iterable is list ? never : list<T>)
*/
function iteratorToList(iterable $iterable): array {
$list = [];
foreach ($iterable as $item) {
$list[] = $item;
}
return $list;
}

/**
* @return iterable<string, string>
*/
function getItems(): iterable {
yield 'a' => 'foo';
yield 'b' => 'bar';
}

// Bug: when reassigning to the same variable, conditional return type resolves incorrectly
$items = getItems();
$items = iteratorToList($items);
assertType('list<string>', $items);

// Works fine when using a different variable
$x = getItems();
$items2 = iteratorToList($x);
assertType('list<string>', $items2);
Loading