From 4197fd6703336513056fe74d84ee451e115fd4c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Bundyra?= Date: Wed, 16 Oct 2024 07:47:07 +0100 Subject: [PATCH] fix: Classes\NoNullValuesSniff for explicit nullable types (#206) Fixes #201 --- .../Sniffs/Classes/NoNullValuesSniff.php | 17 ++++++++++++++--- test/Sniffs/Classes/NoNullValuesUnitTest.inc | 4 ++++ .../Classes/NoNullValuesUnitTest.inc.fixed | 4 ++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/WebimpressCodingStandard/Sniffs/Classes/NoNullValuesSniff.php b/src/WebimpressCodingStandard/Sniffs/Classes/NoNullValuesSniff.php index 601e1025..d6987fa6 100644 --- a/src/WebimpressCodingStandard/Sniffs/Classes/NoNullValuesSniff.php +++ b/src/WebimpressCodingStandard/Sniffs/Classes/NoNullValuesSniff.php @@ -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; @@ -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'; diff --git a/test/Sniffs/Classes/NoNullValuesUnitTest.inc b/test/Sniffs/Classes/NoNullValuesUnitTest.inc index 80d1c95c..515dc7bc 100644 --- a/test/Sniffs/Classes/NoNullValuesUnitTest.inc +++ b/test/Sniffs/Classes/NoNullValuesUnitTest.inc @@ -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; } diff --git a/test/Sniffs/Classes/NoNullValuesUnitTest.inc.fixed b/test/Sniffs/Classes/NoNullValuesUnitTest.inc.fixed index a7ba2554..656aedbc 100644 --- a/test/Sniffs/Classes/NoNullValuesUnitTest.inc.fixed +++ b/test/Sniffs/Classes/NoNullValuesUnitTest.inc.fixed @@ -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; }