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

namespace Rector\Tests\DowngradePhp82\Rector\FuncCall\DowngradeIteratorCountToArrayRector\Fixture;

final class SkipInternary
{
public function run($taggedServices)
{
return \is_array($taggedServices) ? $taggedServices : \iterator_to_array($taggedServices);
}

public function run2($taggedServices)
{
return ! \is_array($taggedServices) ? \iterator_to_array($taggedServices): $taggedServices;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Rector\Tests\DowngradePhp82\Rector\FuncCall\DowngradeIteratorCountToArrayRector\Fixture;

final class SkipNullableTraversable
{
function test(?\Traversable $data)
{
$c = iterator_count($data);
$v = iterator_to_array($data);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\NodeTraverser;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use Rector\NodeAnalyzer\ArgsAnalyzer;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
Expand All @@ -26,7 +29,8 @@
final class DowngradeIteratorCountToArrayRector extends AbstractRector
{
public function __construct(
private readonly ArgsAnalyzer $argsAnalyzer
private readonly ArgsAnalyzer $argsAnalyzer,
private readonly BetterNodeFinder $betterNodeFinder
) {
}

Expand All @@ -35,7 +39,7 @@ public function __construct(
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
return [Ternary::class, FuncCall::class];
}

public function getRuleDefinition(): RuleDefinition
Expand Down Expand Up @@ -63,10 +67,23 @@ function test(array|Traversable $data) {
}

/**
* @param FuncCall $node
* @param Ternary|FuncCall $node
*/
public function refactor(Node $node): ?Node
public function refactor(Node $node): null|FuncCall|int
{
if ($node instanceof Ternary) {
$hasIsArrayCheck = (bool) $this->betterNodeFinder->findFirst(
$node,
fn (Node $subNode): bool => $subNode instanceof FuncCall && $this->isName($subNode, 'is_array')
);

if ($hasIsArrayCheck) {
return NodeTraverser::DONT_TRAVERSE_CHILDREN;
}

return null;
}

if (! $this->isNames($node, ['iterator_count', 'iterator_to_array'])) {
return null;
}
Expand Down Expand Up @@ -107,6 +124,7 @@ private function shouldSkip(Type $type): bool
return false;
}

$type = TypeCombinator::removeNull($type);
return $type->isObject()
->yes();
}
Expand Down
Loading