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

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

final class WrapMixedOnce
{
public function run($data)
{
return iterator_to_array($data);
}
}

?>
-----
<?php

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

final class WrapMixedOnce
{
public function run($data)
{
return iterator_to_array(is_array($data) ? new \ArrayIterator($data) : $data);
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Ternary;
Expand Down Expand Up @@ -81,6 +82,12 @@ public function refactor(Node $node): null|FuncCall
return null;
}

// already wrapped in a previous pass; the wrap type stays not-yes-object (e.g. ArrayIterator|mixed),
// so without this check it would be wrapped again on every pass
if ($this->isArrayIteratorWrapped($arg->value)) {
return null;
}

$type = $this->nodeTypeResolver->getType($arg->value);
if ($this->shouldSkip($type)) {
return null;
Expand All @@ -100,6 +107,23 @@ public function refactor(Node $node): null|FuncCall
return $node;
}

private function isArrayIteratorWrapped(Expr $expr): bool
{
if (! $expr instanceof Ternary) {
return false;
}

if (! $expr->cond instanceof FuncCall || ! $this->isName($expr->cond, 'is_array')) {
return false;
}

if (! $expr->if instanceof New_) {
return false;
}

return $this->isName($expr->if->class, 'ArrayIterator');
}

private function shouldSkip(Type $type): bool
{
if ($type->isArray()->yes()) {
Expand Down
Loading