diff --git a/rules-tests/TypedCollections/Rector/ClassMethod/RemoveNullFromNullableCollectionTypeRector/Fixture/remove_from_nullable_property_type.php.inc b/rules-tests/TypedCollections/Rector/ClassMethod/RemoveNullFromNullableCollectionTypeRector/Fixture/remove_from_nullable_property_type.php.inc new file mode 100644 index 00000000..f8a61477 --- /dev/null +++ b/rules-tests/TypedCollections/Rector/ClassMethod/RemoveNullFromNullableCollectionTypeRector/Fixture/remove_from_nullable_property_type.php.inc @@ -0,0 +1,43 @@ + + */ + private ?Collection $collection; + + public function __construct() + { + $this->collection = new ArrayCollection([]); + } +} + +?> +----- + + */ + private Collection $collection; + + public function __construct() + { + $this->collection = new ArrayCollection([]); + } +} + +?> diff --git a/rules/TypedCollections/Rector/ClassMethod/RemoveNullFromNullableCollectionTypeRector.php b/rules/TypedCollections/Rector/ClassMethod/RemoveNullFromNullableCollectionTypeRector.php index f653776b..5deae516 100644 --- a/rules/TypedCollections/Rector/ClassMethod/RemoveNullFromNullableCollectionTypeRector.php +++ b/rules/TypedCollections/Rector/ClassMethod/RemoveNullFromNullableCollectionTypeRector.php @@ -39,7 +39,7 @@ public function __construct( public function getRuleDefinition(): RuleDefinition { return new RuleDefinition( - 'Remove null from a nullable Collection, as empty ArrayCollection is preferred instead to keep property type strict and always a collection', + 'Remove null from a nullable Collection, as empty ArrayCollection is preferred instead to keep property/class method type strict and always a collection', [ new CodeSample( <<<'CODE_SAMPLE' @@ -128,6 +128,13 @@ private function refactorClassMethod(ClassMethod $classMethod): null|ClassMethod private function refactorProperty(Property $property): ?Property { + if ($property->type instanceof NullableType && $this->hasNativeCollectionType($property->type)) { + // unwrap nullable type + $property->type = $property->type->type; + + return $property; + } + if (! $this->hasNativeCollectionType($property)) { return null; } @@ -186,12 +193,12 @@ private function refactorProperty(Property $property): ?Property return $property; } - private function hasNativeCollectionType(Property $property): bool + private function hasNativeCollectionType(Property|NullableType $node): bool { - if (! $property->type instanceof Name) { + if (! $node->type instanceof Name) { return false; } - return $this->isName($property->type, DoctrineClass::COLLECTION); + return $this->isName($node->type, DoctrineClass::COLLECTION); } }