Skip to content

Commit 1543263

Browse files
committed
PropertyTypeHintSniff: Improved fixer for nullable properties
1 parent 26a509a commit 1543263

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

SlevomatCodingStandard/Sniffs/TypeHints/PropertyTypeHintSniff.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,16 @@
1919
use SlevomatCodingStandard\Helpers\TypeHintHelper;
2020
use function array_map;
2121
use function count;
22+
use function in_array;
2223
use function sprintf;
2324
use const PHP_VERSION_ID;
25+
use const T_COMMA;
2426
use const T_DOC_COMMENT_CLOSE_TAG;
2527
use const T_DOC_COMMENT_STAR;
2628
use const T_PRIVATE;
2729
use const T_PROTECTED;
2830
use const T_PUBLIC;
31+
use const T_SEMICOLON;
2932
use const T_STATIC;
3033
use const T_VAR;
3134
use const T_VARIABLE;
@@ -201,6 +204,15 @@ private function checkTypeHint(File $phpcsFile, int $propertyPointer, ?PropertyT
201204

202205
$phpcsFile->fixer->beginChangeset();
203206
$phpcsFile->fixer->addContent($propertyStartPointer, sprintf(' %s%s', ($nullableTypeHint ? '?' : ''), $propertyTypeHint));
207+
208+
if ($nullableTypeHint) {
209+
$pointerAfterProperty = TokenHelper::findNextEffective($phpcsFile, $propertyPointer + 1);
210+
$tokens = $phpcsFile->getTokens();
211+
if (in_array($tokens[$pointerAfterProperty]['code'], [T_SEMICOLON, T_COMMA], true)) {
212+
$phpcsFile->fixer->addContent($propertyPointer, ' = null');
213+
}
214+
}
215+
204216
$phpcsFile->fixer->endChangeset();
205217
}
206218

tests/Sniffs/TypeHints/data/propertyTypeHintEnabledNativeErrors.fixed.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@ class Whatever
1313
/**
1414
* @var int[]|null
1515
*/
16-
public ?array $arrayTypeHintWithNull;
16+
public ?array $arrayTypeHintWithNull = null;
1717

1818
/**
1919
* @var array{foo: int}
2020
*/
2121
public array $arrayShapeTypeHint;
2222

23-
public ?string $twoTypeWithNull;
23+
public ?string $twoTypeWithNull = null;
2424

2525
/**
2626
* @var int[]|\Traversable
@@ -69,7 +69,7 @@ class Whatever
6969
/**
7070
* @var null|\Traversable
7171
*/
72-
public ?\Traversable $traversableNull;
72+
public ?\Traversable $traversableNull = null;
7373

7474
public object $object;
7575

0 commit comments

Comments
 (0)