From c4845ed7c6f58a2979443c20aa3d569ddcc6a2a8 Mon Sep 17 00:00:00 2001 From: Tim Date: Tue, 18 Mar 2025 22:15:38 +0100 Subject: [PATCH] First fully working recursive bundler --- bundle.php | 68 +++++++++++++++++++++++++++++++---------------- test.include.php | 4 ++- test2.include.php | 3 +++ 3 files changed, 51 insertions(+), 24 deletions(-) create mode 100644 test2.include.php diff --git a/bundle.php b/bundle.php index 84116cd..a88f3a9 100755 --- a/bundle.php +++ b/bundle.php @@ -6,36 +6,58 @@ function line(string $text): void echo $text . PHP_EOL; } -if (count($argv) < 2) { - line('Usage: bundle.php '); +if (count($argv) < 3) { + line('Usage: bundle.php '); exit(1); } -$targetFile = $argv[1]; -if (!file_exists($targetFile)) { - line('File not found: ' . $targetFile); +$fromFile = $argv[1]; +if (!file_exists($fromFile)) { + line('File not found: ' . $fromFile); + exit(1); +} +$toFile = $argv[2]; +if (file_exists($toFile)) { + line('File already exists: ' . $toFile); exit(1); } -function getIncludes(string $file): array +function getLineIncludeFile(string $line): false|string { - $content = file_get_contents($file); - $files = []; - foreach (explode("\n", $content) as $line) { - if (str_starts_with($line, 'include')) { - $line = "include 'test.include.php';"; - preg_match("/include\s+'([^']+)'/", $line, $matches); - $files[] = $matches[1]; + if (str_starts_with($line, 'include')) { + preg_match("/include\s+'([^']+)'/", $line, $matches); + return $matches[1]; + } + return false; +} + +function getAllLines(string $file): iterable +{ + $handle = fopen($file, 'r'); + while (!feof($handle)) { + yield fgets($handle); + } + fclose($handle); +} + +function replaceIncludes(string $file, int $depth = 0): iterable +{ + foreach (getAllLines($file) as $line) { + $includeFile = getLineIncludeFile($line); + if ($includeFile) { + yield from replaceIncludes($includeFile, $depth + 1); + } else { + if ($depth > 0 && str_starts_with($line, '