Skip to content

Commit

Permalink
Improve type inference for coalesce
Browse files Browse the repository at this point in the history
  • Loading branch information
rvanvelzen committed Sep 9, 2022
1 parent fb08fb5 commit 3cb5950
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -1281,11 +1281,13 @@ private function createForExpr(

if (
$scope !== null
&& $context->true()
&& !$context->null()
&& $expr instanceof Expr\BinaryOp\Coalesce
&& $type->isSuperTypeOf($scope->getType($expr->right))->no()
) {
$expr = $expr->left;
$rightIsSuperType = $type->isSuperTypeOf($scope->getType($expr->right));
if (($context->true() && $rightIsSuperType->no()) || ($context->false() && $rightIsSuperType->yes())) {
$expr = $expr->left;
}
}

if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1157,4 +1157,10 @@ public function testBug7156(): void
$this->analyse([__DIR__ . '/data/bug-7156.php'], []);
}

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

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

namespace Bug7973;

use DateTime;
use DateTimeZone;
use Exception;
use InvalidArgumentException;

function createFromString(string $timespec): DateTime {
try {
return new DateTime($timespec, new DateTimeZone('UTC'));
} catch (Exception) {
throw new InvalidArgumentException(sprintf('Invalid timespec "%s"', $timespec));
}
}

function () {
$rows = [
['timespec'=>null],
['timespec'=>'2020-01-01T01:02:03+08:00'],
];

$result = [];
foreach($rows as $row) {
$result[] = ($row['timespec'] ?? null) !== null ? createFromString($row['timespec']) : null;
}
};

0 comments on commit 3cb5950

Please sign in to comment.