<?php

function findFilesWithWriteFunctions($dir) {
    $directory = new RecursiveDirectoryIterator($dir);
    $iterator = new RecursiveIteratorIterator($directory);
    $phpFiles = new RegexIterator($iterator, '/^.+\.php$/i');

    $writeFunctions = ['file_put_contents', 'fwrite', 'fputs', 'fputcsv'];
    // Atualize o padrão para capturar também o nome do arquivo após a função de escrita
    $pattern = '/\b(' . implode('|', $writeFunctions) . ')\s*\(\s*["\']?([^,"\']+)["\']?/';

    $foundFiles = [];

    foreach ($phpFiles as $file) {
        $filePath = $file->getPathname(); // Atualização para obter o caminho correto do arquivo
        $content = file_get_contents($filePath);
        // Use preg_match_all para encontrar todas as ocorrências
        if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                // $match[1] é a função de escrita, $match[2] é o nome do arquivo alvo
                $foundFiles[] = $filePath . ' (' . $match[1] . ' to ' . $match[2] . ')';
            }
        }
    }

    return $foundFiles;
}

// Uso da função
$directoryPath = './'; // Substitua pelo caminho do diretório
$filesWithWriteFunctions = findFilesWithWriteFunctions($directoryPath);

// Exibir os arquivos encontrados
foreach ($filesWithWriteFunctions as $file) {
    echo $file . "\n";
}

?>

