Skip to content

Commit e7d904c

Browse files
authored
[DowngradePhp81] Fix nullable param on DowngradeNewInInitializerRector (#245)
1 parent 08149e6 commit e7d904c

File tree

3 files changed

+16
-19
lines changed

3 files changed

+16
-19
lines changed

rules-tests/DowngradePhp81/Rector/FunctionLike/DowngradeNewInInitializerRector/Fixture/new_not_promoted.php.inc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ final class NewNotPromoted
2222
{
2323
public stdClass $obj;
2424

25-
public function __construct(stdClass $obj = null)
25+
public function __construct(?stdClass $obj = null)
2626
{
2727
$obj ??= new stdClass;
2828
$this->obj = $obj;

rules/DowngradePhp81/Rector/FunctionLike/DowngradeNewInInitializerRector.php

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,11 @@ private function replaceNewInParams(ClassMethod|Closure|Function_ $functionLike)
175175
$assign = new AssignCoalesce($param->var, $default);
176176
}
177177

178+
// recheck after
179+
if ($isConstructor) {
180+
$param->type = $this->ensureNullableType($param->type);
181+
}
182+
178183
$stmts[] = new Expression($assign);
179184

180185
$param->default = $this->nodeFactory->createNull();
@@ -201,28 +206,20 @@ private function ensureNullableType(Name|Identifier|ComplexType $type): Nullable
201206
}
202207

203208
if ($type instanceof UnionType) {
204-
if (! $this->hasNull($type)) {
205-
$type->types[] = new Name('null');
209+
foreach ($type->types as $typeChild) {
210+
if (! $typeChild instanceof Identifier) {
211+
continue;
212+
}
213+
214+
if ($typeChild->toLowerString() === 'null') {
215+
return $type;
216+
}
206217
}
207218

219+
$type->types[] = new Identifier('null');
208220
return $type;
209221
}
210222

211223
throw new ShouldNotHappenException();
212224
}
213-
214-
private function hasNull(UnionType $unionType): bool
215-
{
216-
foreach ($unionType->types as $type) {
217-
if (! $type instanceof Identifier) {
218-
continue;
219-
}
220-
221-
if ($type->toLowerString() === 'null') {
222-
return true;
223-
}
224-
}
225-
226-
return false;
227-
}
228225
}

tests/Issues/DowngradeNewInArrayInitializerPromotion/Fixture/new_in_array.php.inc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class NewInArray
3333
/**
3434
* @param array<string, object> $property
3535
*/
36-
public function __construct(array $property = null)
36+
public function __construct(?array $property = null)
3737
{
3838
$property ??= [
3939
'a' => new stdClass()

0 commit comments

Comments
 (0)