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

Improve type inference for coalesce #1716

Merged
merged 1 commit into from
Sep 13, 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
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;
}
};