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,49 @@
<?php

declare(strict_types=1);

namespace Rector\Doctrine\Tests\TypedCollections\Rector\FuncCall\ArrayMapOnCollectionToArrayRector\Fixture;

use Doctrine\Common\Collections\Collection;

final class ArrayFilterToArray
{
/**
* @var Collection<int, string>
*/
public $items;

public function merge()
{
$items = $this->items;

return array_filter($items, fn ($item) => $item);
}
}

?>
-----
<?php

declare(strict_types=1);

namespace Rector\Doctrine\Tests\TypedCollections\Rector\FuncCall\ArrayMapOnCollectionToArrayRector\Fixture;

use Doctrine\Common\Collections\Collection;

final class ArrayFilterToArray
{
/**
* @var Collection<int, string>
*/
public $items;

public function merge()
{
$items = $this->items;

return array_filter($items->toArray(), fn ($item) => $item);
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Rector\Doctrine\Tests\TypedCollections\Rector\FuncCall\ArrayMapOnCollectionToArrayRector\Fixture;

final class SkipNonCollection
{
/**
* @var array<int, string>
*/
public $items;

public function merge()
{
$items = $this->items;

return array_filter($items, fn ($item) => $item);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function __construct(
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Change array_map on Collection typed property to ->toArray() call, to always provide an array',
'Change array_map() and array_filter() on Collection typed property to ->toArray() call, to always provide an array',
[
new CodeSample(
<<<'CODE_SAMPLE'
Expand Down Expand Up @@ -84,18 +84,38 @@ public function refactor(Node $node): ?FuncCall
return null;
}

if (! $this->isName($node->name, 'array_map')) {
return null;
if ($this->isName($node->name, 'array_map')) {
return $this->refactorArrayMap($node);
}

if ($this->isName($node->name, 'array_filter')) {
$this->refactorArrayFilter($node);
}

$secondArg = $node->getArgs()[1];
return null;
}

private function refactorArrayMap(FuncCall $funcCall): null|FuncCall
{
$secondArg = $funcCall->getArgs()[1];
if (! $this->collectionTypeDetector->isCollectionType($secondArg->value)) {
return null;
}

$secondArg->value = new MethodCall($secondArg->value, 'toArray');

return $node;
return $funcCall;
}

private function refactorArrayFilter(FuncCall $funcCall): ?FuncCall
{
$firstArg = $funcCall->getArgs()[0];
if (! $this->collectionTypeDetector->isCollectionType($firstArg->value)) {
return null;
}

$firstArg->value = new MethodCall($firstArg->value, 'toArray');

return $funcCall;
}
}