Skip to content

Commit

Permalink
NullableTypeDeclarationForDefaultNullValueFixer - support union types
Browse files Browse the repository at this point in the history
  • Loading branch information
keradus committed Jan 21, 2021
1 parent f7b5245 commit 0f20987
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,14 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens)
private function fixFunctionParameters(Tokens $tokens, array $arguments)
{
foreach (array_reverse($arguments) as $argumentInfo) {
// If the parameter doesn't have a type declaration or a default value null we can continue
if (
// Skip, if the parameter
// - doesn't have a type declaration
!$argumentInfo->hasTypeAnalysis()
|| !$argumentInfo->hasDefault()
|| 'null' !== strtolower($argumentInfo->getDefault())
// type is a union
|| false !== strpos($argumentInfo->getTypeAnalysis()->getName(), '|')
// - a default value is not null we can continue
|| !$argumentInfo->hasDefault() || 'null' !== strtolower($argumentInfo->getDefault())
) {
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,12 +417,12 @@ public function testFix80($expected, $input = null)

public function provideFix80Cases()
{
yield [
yield 'trailing comma' => [
'<?php function foo(?string $param = null,) {}',
'<?php function foo(string $param = null,) {}',
];

yield [
yield 'property promotion' => [
'<?php class Foo {
public function __construct(
public ?string $paramA = null,
Expand All @@ -433,5 +433,13 @@ public function __construct(
) {}
}',
];

yield 'don\'t change union types' => [
'<?php class Foo {
public function __construct(private int | null $bar = null, $baz = 1) {}
public function aaa(int | string $bar = null, $baz = 1) {}
public function bbb(int | null $bar = null, $baz = 1) {}
}',
];
}
}

0 comments on commit 0f20987

Please sign in to comment.