Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Rector\Doctrine\Tests\TypedCollections\Rector\ClassMethod\RemoveNullFromNullableCollectionTypeRector\Fixture;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

final class RemoveFromNullablePropertyType
{
/**
* @var Collection<int, string>
*/
private ?Collection $collection;

public function __construct()
{
$this->collection = new ArrayCollection([]);
}
}

?>
-----
<?php

namespace Rector\Doctrine\Tests\TypedCollections\Rector\ClassMethod\RemoveNullFromNullableCollectionTypeRector\Fixture;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

final class RemoveFromNullablePropertyType
{
/**
* @var Collection<int, string>
*/
private Collection $collection;

public function __construct()
{
$this->collection = new ArrayCollection([]);
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
}
}