Skip to content
Closed
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
6 changes: 4 additions & 2 deletions src/Rules/Variables/NullCoalesceRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PHPStan\Rules\Rule;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use PHPStan\Type\VoidType;

/**
* @implements Rule<Node\Expr>
Expand All @@ -27,12 +28,13 @@ public function getNodeType(): string
public function processNode(Node $node, Scope $scope): array
{
$typeMessageCallback = static function (Type $type): ?string {
$isVoid = (new VoidType())->isSuperTypeOf($type);
$isNull = (new NullType())->isSuperTypeOf($type);
if ($isNull->maybe()) {
if ($isNull->maybe() || $isVoid->maybe()) {
return null;
}

if ($isNull->yes()) {
if ($isNull->yes() || $isVoid->yes()) {
return 'is always null';
}

Expand Down
13 changes: 13 additions & 0 deletions tests/PHPStan/Rules/Variables/NullCoalesceRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -368,4 +368,17 @@ public function testBug8084(): void
$this->analyse([__DIR__ . '/data/bug-8084.php'], []);
}

public function testVoid(): void
{
$this->treatPhpDocTypesAsCertain = true;
$this->strictUnnecessaryNullsafePropertyFetch = true;

$this->analyse([__DIR__ . '/data/null-coalesce-void.php'], [
[
'Expression on left side of ?? is always null.',
22,
],
]);
}

}
22 changes: 22 additions & 0 deletions tests/PHPStan/Rules/Variables/data/null-coalesce-void.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php // lint >= 8.0

namespace CoalesceRuleVoid;

/** @return array|void */
function get_post_custom_keys($maybe = false)
{
if ($maybe) {
return;
}

return [];
}

function foo_bar(): void
{
return;
}

$test1 = get_post_custom_keys(true) ?? 'foo';

$test2 = foo_bar() ?? 'bar';