Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-14213.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php declare(strict_types = 1);

namespace Bug14213;

use function PHPStan\Testing\assertType;

class HelloWorld
{
public static function coalesce_nonsensical(): void
{
$x0 = $x1 = $x2 = null;

if (rand(0, 1)) {
$x0 = rand(0, 1);
$x1 = rand(2, 3);
$x2 = rand(4, 5);
}

// either all 3 variables are null, or all have a int-range value
$x = (
$x0 ??
$x1 ??
$x2
);

assertType('int<0, 1>|null', $x);
}

public static function coalesce_int_ranges(): void
{
$x0 = $x1 = $x2 = null;

if (rand(0, 1)) {
$x0 = rand(0, 1);
}
if (rand(0, 1)) {
$x1 = rand(2, 3);
}
if (rand(0, 1)) {
$x2 = rand(4, 5);
}

$x = (
$x0 ??
$x1 ??
$x2
);

assertType('int<0, 5>|null', $x);
}

public static function coalesce_int_range_after_maybe_defined(): void
{
$x0 = $x1 = $x2 = null;

if (rand(0, 1)) {
$maybeDefined = 10;
}
if (rand(0, 1)) {
$x0 = rand(0, 1);
}
if (rand(0, 1)) {
$x1 = rand(2, 3);
}
if (rand(0, 1)) {
$x2 = rand(4, 5);
}

$x = (
$maybeDefined ??
$x0 ??
$x1 ??
$x2
);

assertType('10|int<0, 5>|null', $x);
}

public static function coalesce_int_range_with_last_non_nullable(): void
{
$x0 = $x1 = null;
$x2 = 20;

if (rand(0, 1)) {
$x0 = rand(0, 1);
}
if (rand(0, 1)) {
$x1 = rand(2, 3);
}
if (rand(0, 1)) {
$x2 = rand(4, 5);
}

$x = (
$x0 ??
$x1 ??
$x2 // cannot be null
);

assertType('20|int<0, 5>', $x);
}
}
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/Variables/NullCoalesceRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -352,4 +352,14 @@ public function testPr4372(): void
$this->analyse([__DIR__ . '/data/pr-4372-null-coalesce.php'], []);
}

public function testBug14213(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-14213.php'], [
[
'Variable $x1 on left side of ?? always exists and is always null.',
22,
],
]);
}

}
Loading