Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix specifying types for chained assignments #1473

Merged
merged 1 commit into from Jun 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 35 additions & 2 deletions src/Analyser/TypeSpecifier.php
Expand Up @@ -1155,10 +1155,43 @@ public function create(
return new SpecifiedTypes([], [], false, [], $rootExpr);
}

while ($expr instanceof Expr\Assign) {
$expr = $expr->var;
$specifiedExprs = [];

if ($expr instanceof Expr\Assign) {
$specifiedExprs[] = $expr->var;

while ($expr->expr instanceof Expr\Assign) {
$specifiedExprs[] = $expr->expr->var;
$expr = $expr->expr;
}
} else {
$specifiedExprs[] = $expr;
}

$types = null;

foreach ($specifiedExprs as $specifiedExpr) {
$newTypes = $this->createForExpr($specifiedExpr, $type, $context, $overwrite, $scope, $rootExpr);

if ($types === null) {
$types = $newTypes;
} else {
$types = $types->unionWith($newTypes);
}
}

return $types;
}

private function createForExpr(
Expr $expr,
Type $type,
TypeSpecifierContext $context,
bool $overwrite = false,
?Scope $scope = null,
?Expr $rootExpr = null,
): SpecifiedTypes
{
if ($scope !== null) {
if ($context->true()) {
$resultType = TypeCombinator::intersect($scope->getType($expr), $type);
Expand Down
Expand Up @@ -416,4 +416,10 @@ public function testBug7229(): void
]);
}

public function testBug7142(): void
{
$this->checkExplicitMixed = true;
$this->analyse([__DIR__ . '/data/bug-7142.php'], []);
}

}
26 changes: 26 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/bug-7142.php
@@ -0,0 +1,26 @@
<?php declare(strict_types = 1);

namespace Bug7142;

/**
* @return array{id: int}|null
*/

function maybeNull(){
if ((rand(3)%2) != 0) {
return ['id' => 1];
}
return null;
}

/**
* @return void
*/
function foo(){
if (!is_null($a = $b = $c = maybeNull())){
echo $a['id'];
echo $b['id']; // 20 "Offset 'id' does not exist on array{id: int}|null."
echo $c['id']; // 21 "Offset 'id' does not exist on array{id: int}|null."
}
}