Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: treat void as null for null coalescing operator #2494

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

Closed
kesselb wants to merge 1 commit into phpstan:1.11.x from kesselb:void-nullcoalesce
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
View file Open in desktop
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
View file Open in desktop
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
View file Open in desktop
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';

AltStyle によって変換されたページ (->オリジナル) /