<commit_before><?php

declare(strict_types=1);

namespace Rector\CodeQuality\Rector\Foreach_;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\If_;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;

/**
 * @see \Rector\CodeQuality\Tests\Rector\Foreach_\SimplifyForeachToArrayFilterRector\SimplifyForeachToArrayFilterRectorTest
 */
final class SimplifyForeachToArrayFilterRector extends AbstractRector
{
    public function getDefinition(): RectorDefinition
    {
        return new RectorDefinition('Simplify foreach with function filtering to array filter', [
            new CodeSample(
                <<<'PHP'
$directories = [];
$possibleDirectories = [];
foreach ($possibleDirectories as $possibleDirectory) {
    if (file_exists($possibleDirectory)) {
        $directories[] = $possibleDirectory;
    }
}
PHP
                ,
                <<<'PHP'
$possibleDirectories = [];
$directories = array_filter($possibleDirectories, 'file_exists');
PHP
            ),
        ]);
    }

    /**
     * @return string[]
     */
    public function getNodeTypes(): array
    {
        return [Foreach_::class];
    }

    /**
     * @param Foreach_ $node
     */
    public function refactor(Node $node): ?Node
    {
        if ($this->shouldSkip($node)) {
            return null;
        }

        /** @var If_ $ifNode */
        $ifNode = $node->stmts[0];

        /** @var FuncCall $funcCallNode */
        $funcCallNode = $ifNode->cond;
        if (count($ifNode->stmts) !== 1) {
            return null;
        }

        if (count($funcCallNode->args) !== 1) {
            return null;
        }

        if (! $this->areNodesEqual($funcCallNode->args[0], $node->valueVar)) {
            return null;
        }

        if (! $ifNode->stmts[0] instanceof Expression) {
            return null;
        }

        $onlyNodeInIf = $ifNode->stmts[0]->expr;
        if (! $onlyNodeInIf instanceof Assign) {
            return null;
        }

        if (! $onlyNodeInIf->var instanceof ArrayDimFetch) {
            return null;
        }

        if (! $this->areNodesEqual($onlyNodeInIf->expr, $node->valueVar)) {
            return null;
        }

        $name = $this->getName($funcCallNode);
        if ($name === null) {
            return null;
        }

        return $this->createAssignNode($node, $name, $onlyNodeInIf->var);
    }

    private function shouldSkip(Foreach_ $foreachNode): bool
    {
        if (count($foreachNode->stmts) !== 1) {
            return true;
        }

        if (! $foreachNode->stmts[0] instanceof If_) {
            return true;
        }

        /** @var If_ $ifNode */
        $ifNode = $foreachNode->stmts[0];

        if ($ifNode->else) {
            return true;
        }

        if ($ifNode->elseifs) {
            return true;
        }

        return ! $ifNode->cond instanceof FuncCall;
    }

    private function createAssignNode(Foreach_ $foreachNode, string $name, ArrayDimFetch $arrayDimFetch): Assign<commit_msg>fixup! Fix else in SimplifyForeachToArrayFilterRector<commit_after><?php

declare(strict_types=1);

namespace Rector\CodeQuality\Rector\Foreach_;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\If_;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;

/**
 * @see \Rector\CodeQuality\Tests\Rector\Foreach_\SimplifyForeachToArrayFilterRector\SimplifyForeachToArrayFilterRectorTest
 */
final class SimplifyForeachToArrayFilterRector extends AbstractRector
{
    public function getDefinition(): RectorDefinition
    {
        return new RectorDefinition('Simplify foreach with function filtering to array filter', [
            new CodeSample(
                <<<'PHP'
$directories = [];
$possibleDirectories = [];
foreach ($possibleDirectories as $possibleDirectory) {
    if (file_exists($possibleDirectory)) {
        $directories[] = $possibleDirectory;
    }
}
PHP
                ,
                <<<'PHP'
$possibleDirectories = [];
$directories = array_filter($possibleDirectories, 'file_exists');
PHP
            ),
        ]);
    }

    /**
     * @return string[]
     */
    public function getNodeTypes(): array
    {
        return [Foreach_::class];
    }

    /**
     * @param Foreach_ $node
     */
    public function refactor(Node $node): ?Node
    {
        if ($this->shouldSkip($node)) {
            return null;
        }

        /** @var If_ $ifNode */
        $ifNode = $node->stmts[0];

        /** @var FuncCall $funcCallNode */
        $funcCallNode = $ifNode->cond;
        if (count($ifNode->stmts) !== 1) {
            return null;
        }

        if (count($funcCallNode->args) !== 1) {
            return null;
        }

        if (! $this->areNodesEqual($funcCallNode->args[0], $node->valueVar)) {
            return null;
        }

        if (! $ifNode->stmts[0] instanceof Expression) {
            return null;
        }

        $onlyNodeInIf = $ifNode->stmts[0]->expr;
        if (! $onlyNodeInIf instanceof Assign) {
            return null;
        }

        if (! $onlyNodeInIf->var instanceof ArrayDimFetch) {
            return null;
        }

        if (! $this->areNodesEqual($onlyNodeInIf->expr, $node->valueVar)) {
            return null;
        }

        $name = $this->getName($funcCallNode);
        if ($name === null) {
            return null;
        }

        return $this->createAssignNode($node, $name, $onlyNodeInIf->var);
    }

    private function shouldSkip(Foreach_ $foreachNode): bool
    {
        if (count($foreachNode->stmts) !== 1) {
            return true;
        }

        if (! $foreachNode->stmts[0] instanceof If_) {
            return true;
        }

        /** @var If_ $ifNode */
        $ifNode = $foreachNode->stmts[0];

        if ($ifNode->else !== null) {
            return true;
        }

        if ($ifNode->elseifs) {
            return true;
        }

        return ! $ifNode->cond instanceof FuncCall;
    }

    private function createAssignNode(Foreach_ $foreachNode, string $name, ArrayDimFetch $arrayDimFetch): Assign
{'fraction_non_alphanumeric': 0.1271936403179841, 'fraction_numerical': 0.002999850007499625, 'mean_word_length': 2.2766584766584765, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 51, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6002991', 'n_tokens_mistral': 2046, 'n_tokens_neox': 1984, 'n_words': 392}