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
12 changes: 12 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,7 @@ private function resolveType(string $exprString, Expr $node): Type
!$node instanceof Variable
&& !$node instanceof Expr\Closure
&& !$node instanceof Expr\ArrowFunction
&& !$this->expressionHasNewInChain($node)
&& $this->hasExpressionType($node)->yes()
) {
return $this->expressionTypes[$exprString]->getType();
Expand All @@ -988,6 +989,17 @@ private function resolveType(string $exprString, Expr $node): Type
return new MixedType();
}

private function expressionHasNewInChain(Expr $expr): bool
{
if ($expr instanceof MethodCall || $expr instanceof PropertyFetch || $expr instanceof Expr\NullsafeMethodCall || $expr instanceof Expr\NullsafePropertyFetch || $expr instanceof Expr\ArrayDimFetch) {
return $expr->var instanceof Expr\New_ || $this->expressionHasNewInChain($expr->var);
}
if (($expr instanceof Expr\StaticCall || $expr instanceof Expr\StaticPropertyFetch || $expr instanceof Expr\ClassConstFetch) && $expr->class instanceof Expr) {
return $expr->class instanceof Expr\New_ || $this->expressionHasNewInChain($expr->class);
}
return false;
}

/**
* @param callable(Type): ?bool $typeCallback
*/
Expand Down
36 changes: 36 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-8985.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php // lint >= 8.0

declare(strict_types = 1);

namespace Bug8985;

use function PHPStan\Testing\assertType;

class Entity
{
public function __construct(private string $value)
{
}

public function getValue(): string
{
return $this->value;
}
}

class Repository
{
/** @return array<int, Entity> */
public function getAll(): array
{
return [new Entity('test')];
}
}

function () : void {
assert((new Repository())->getAll() === []);

$all = (new Repository())->getAll();
assertType('array<int, Bug8985\Entity>', $all);
$value = $all[0]->getValue();
};
Loading