Skip to content

Commit

Permalink
Fix EnsureExplicitNullableTypes (#1716)
Browse files Browse the repository at this point in the history
Improve the regexp pattern to
* allow "mixed"
* allow fqcn (\Foo) & aliases (Foo\Bar)

Improve line number reporting (replace #1714)
  • Loading branch information
smnandre authored Apr 17, 2024
1 parent e7b1f3c commit 481cebd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/Rule/EnsureExplicitNullableTypes.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,15 @@ public function check(Lines $lines, int $number, string $filename): ViolationInt
$lines->next();

while ($lines->valid() && !$lines->current()->isDirective()) {
++$number;

if (!str_contains((string) $lines->current()->clean(), ' = null')) {
$lines->next();

continue;
}

$pattern = '/([?]?\w+)\s+\$(\w+)\s*=\s*null(?=\s*[,\)])/';
$pattern = '#((?:\??\\\\?\w+[|]?)+)\s+\$(\w+)\s*=\s*null(?=\s*[,\)])#siu';

if ($matches = $lines->current()->clean()->match($pattern, \PREG_SET_ORDER)) {
foreach ($matches as $match) {
Expand All @@ -65,6 +67,11 @@ public function check(Lines $lines, int $number, string $filename): ViolationInt
continue;
}

// mixed $id = null
if ('mixed' === $types) {
continue;
}

// int|string|null $id = null
$types = explode('|', $types);

Expand Down
19 changes: 16 additions & 3 deletions tests/Rule/EnsureExplicitNullableTypesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,21 @@ public static function validProvider(): iterable
$validCases = [
'function foo(int $bar = 23)',
'function foo(?int $bar = null)',
'function foo(?\\Throwable $exception = null)',
'function foo(\\Throwable|null $exception = null)',
'function foo(?Foo\\Bar $bar = null)',
'function foo(mixed $bar = null)',
'function foo(int|null $bar = null)',
'function foo(int|string|null $bar = null)',
];

foreach ($validCases as $validCase) {
yield $validCase => [
NullViolation::create(),
new RstSample(['.. code-block:: php', $validCase]),
new RstSample([
'.. code-block:: php',
' '.$validCase,
]),
];
}
}
Expand All @@ -63,6 +70,9 @@ public static function invalidProvider(): iterable
{
$invalidCases = [
'public function foo(int $bar = null)',
'public function foo(Throwable $bar = null)',
'public function foo(Foo\\Bar $bar = null)',
'public function foo(\\Throwable $bar = null)',
'public function foo(int|string $bar = null)',
'function foo(int $foo, int $bar = null)',
'function foo(int $foo, int $bar = null, int $baz)',
Expand All @@ -76,10 +86,13 @@ public static function invalidProvider(): iterable
Violation::from(
'Please use explicit nullable types.',
'filename',
1,
2,
$invalidCase,
),
new RstSample(['.. code-block:: php', $invalidCase]),
new RstSample([
'.. code-block:: php',
' '.$invalidCase,
]),
];
}
}
Expand Down

0 comments on commit 481cebd

Please sign in to comment.