Skip to content
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

fix: Classes\NoNullValuesSniff for explicit nullable types #206

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
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;
}
Loading