Skip to content

Commit

Permalink
fix: Classes\NoNullValuesSniff for explicit nullable types
Browse files Browse the repository at this point in the history
  • Loading branch information
michalbundyra committed Oct 16, 2024
1 parent 94cd55e commit 944ac73
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/WebimpressCodingStandard/Sniffs/Classes/NoNullValuesSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
use PHP_CodeSniffer\Util\Tokens;

use function in_array;
use function strpos;
use function strtolower;
use function substr;

use const T_EQUAL;
use const T_NULL;
Expand All @@ -31,15 +34,23 @@ protected function processMemberVar(File $phpcsFile, $stackPtr) : void
$value = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, true);
if ($tokens[$value]['code'] === T_NULL) {
$props = $phpcsFile->getMemberProperties($stackPtr);
if ($props['type'] !== '' && $props['nullable_type'] === true) {

$type = strtolower($props['type']);

$nullableType = $props['nullable_type'] === true
|| strpos($type, '|null|') !== false
|| strpos($type, 'null|') === 0
|| substr($type, -5) === '|null';

if ($type !== '' && $nullableType === true) {
return;
}

$error = $props['type'] !== '' && $props['nullable_type'] === false
$error = $type !== '' && $nullableType === false
? 'Default null value for not-nullable property is invalid'
: 'Default null value for the property is redundant';

$code = $props['type'] !== '' && $props['nullable_type'] === false
$code = $type !== '' && $nullableType === false
? 'Invalid'
: 'NullValue';

Expand Down
4 changes: 4 additions & 0 deletions test/Sniffs/Classes/NoNullValuesUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,8 @@ class NoNullValues

$string = "String $var = null";
}

public null|int $a1 = null;
public int | null $a2 = null;
public \Countable |null | \Iterable $a3 = null;
}
4 changes: 4 additions & 0 deletions test/Sniffs/Classes/NoNullValuesUnitTest.inc.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@ class NoNullValues

$string = "String $var = null";
}

public null|int $a1 = null;
public int | null $a2 = null;
public \Countable |null | \Iterable $a3 = null;
}

0 comments on commit 944ac73

Please sign in to comment.