<?php
// Simple recursive PHP linter for the workspace
// Usage: php f_scripts/php_lint_all.php

declare(strict_types=1);

function iterPhpFiles(string $dir): Generator {
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
    foreach ($it as $file) {
        if ($file->isFile()) {
            $ext = strtolower($file->getExtension());
            if ($ext === 'php' || ($ext === '' && preg_match('/\\.php$/i', $file->getFilename()))) {
                yield $file->getPathname();
            }
        }
    }
}

$root = realpath(__DIR__ . '/..');
$ok = true;
$count = 0;

foreach (iterPhpFiles($root) as $path) {
    // Skip vendor and cache dirs if present
    if (strpos($path, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR) !== false) continue;
    if (strpos($path, DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR) !== false) continue;

    $cmd = sprintf('php -l %s 2>&1', escapeshellarg($path));
    $out = shell_exec($cmd);
    $count++;
    if (!str_contains((string)$out, 'No syntax errors detected')) {
        $ok = false;
        fwrite(STDERR, $out);
    }
}

if ($ok) {
    echo "OK: {$count} PHP files linted with no syntax errors." . PHP_EOL;
    exit(0);
}

fwrite(STDERR, "Lint failed. See errors above." . PHP_EOL);
exit(1);

