Skip to content

Commit 4197fd6

Browse files
fix: Classes\NoNullValuesSniff for explicit nullable types (#206)
Fixes #201
1 parent 94cd55e commit 4197fd6

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

src/WebimpressCodingStandard/Sniffs/Classes/NoNullValuesSniff.php

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
use PHP_CodeSniffer\Util\Tokens;
1010

1111
use function in_array;
12+
use function strpos;
13+
use function strtolower;
14+
use function substr;
1215

1316
use const T_EQUAL;
1417
use const T_NULL;
@@ -31,15 +34,23 @@ protected function processMemberVar(File $phpcsFile, $stackPtr) : void
3134
$value = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, true);
3235
if ($tokens[$value]['code'] === T_NULL) {
3336
$props = $phpcsFile->getMemberProperties($stackPtr);
34-
if ($props['type'] !== '' && $props['nullable_type'] === true) {
37+
38+
$type = strtolower($props['type']);
39+
40+
$nullableType = $props['nullable_type'] === true
41+
|| strpos($type, '|null|') !== false
42+
|| strpos($type, 'null|') === 0
43+
|| substr($type, -5) === '|null';
44+
45+
if ($type !== '' && $nullableType === true) {
3546
return;
3647
}
3748

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

42-
$code = $props['type'] !== '' && $props['nullable_type'] === false
53+
$code = $type !== '' && $nullableType === false
4354
? 'Invalid'
4455
: 'NullValue';
4556

test/Sniffs/Classes/NoNullValuesUnitTest.inc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,8 @@ class NoNullValues
2828

2929
$string = "String $var = null";
3030
}
31+
32+
public null|int $a1 = null;
33+
public int | null $a2 = null;
34+
public \Countable |null | \Iterable $a3 = null;
3135
}

test/Sniffs/Classes/NoNullValuesUnitTest.inc.fixed

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,8 @@ class NoNullValues
2727

2828
$string = "String $var = null";
2929
}
30+
31+
public null|int $a1 = null;
32+
public int | null $a2 = null;
33+
public \Countable |null | \Iterable $a3 = null;
3034
}

0 commit comments

Comments
 (0)