67 lines
1.5 KiB
PHP
Executable File
67 lines
1.5 KiB
PHP
Executable File
#!/usr/bin/env php
|
|
<?php
|
|
|
|
/**
|
|
* Very simple script, recursively parses a PHP file replacing all includes with the file, no deduplication
|
|
*/
|
|
|
|
function line(string $text): void
|
|
{
|
|
echo $text . PHP_EOL;
|
|
}
|
|
|
|
if (count($argv) < 3) {
|
|
line('Usage: bundle.php <inFile> <outFile>');
|
|
exit(1);
|
|
}
|
|
$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 getLineIncludeFile(string $line): false|string
|
|
{
|
|
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, '<?php')) continue;
|
|
if (empty(trim($line))) continue;
|
|
yield $line;
|
|
}
|
|
}
|
|
}
|
|
|
|
$lines = replaceIncludes($fromFile);
|
|
$toFileHandle = fopen($toFile, 'w');
|
|
foreach ($lines as $line) {
|
|
fwrite($toFileHandle, $line);
|
|
chmod($toFile, fileperms($fromFile));
|
|
}
|
|
fwrite($toFileHandle, PHP_EOL);
|
|
fclose($toFileHandle); |