Skip to content

Instantly share code, notes, and snippets.

@ayDavidGitHere
Created May 27, 2025 12:28
Show Gist options
  • Save ayDavidGitHere/57c462770007b75b5d06d0e26455716b to your computer and use it in GitHub Desktop.
Save ayDavidGitHere/57c462770007b75b5d06d0e26455716b to your computer and use it in GitHub Desktop.
Build PHP File for source files (templates)
<?php
// Usage message with examples
$usage = <<<USAGE
Usage:
php buildFile.php <input_template_file> [output_file]
Examples:
php buildFile.php index.php.bld
php buildFile.php index.php.bld dist/index.php
If no output file is specified, it defaults to removing .bld or appending .out.
USAGE;
if ($argc < 2 || $argc > 3) {
fwrite(STDERR, $usage . "\n");
exit(1);
}
$inputFile = $argv[1];
$outputFile = $argc === 3 ? $argv[2] : preg_replace('/\.bld$/', '', $inputFile);
if (!file_exists($inputFile)) {
fwrite(STDERR, "❌ Error: File not found: $inputFile\n");
exit(1);
}
if ($outputFile === $inputFile) {
$outputFile .= '.out';
}
// Ensure output directory exists
$outputDir = dirname($outputFile);
if (!is_dir($outputDir)) {
if (!mkdir($outputDir, 0775, true)) {
fwrite(STDERR, "❌ Error: Could not create directory $outputDir\n");
exit(1);
}
}
$template = file_get_contents($inputFile);
// Pattern matches {{ bld_temp_src="filename" [bld_escape="value"] }}
$pattern = '/\{\{\s*bld_temp_src\s*=\s*"([^"]+)"(?:\s+bld_escape\s*=\s*"([^"]*)")?\s*\}\}/';
$processed = preg_replace_callback($pattern, function ($matches) use ($inputFile) {
$includeFile = $matches[1];
$escapeType = isset($matches[2]) ? $matches[2] : null;
$baseDir = dirname($inputFile);
$filePath = $includeFile;
if (!file_exists($filePath)) {
return "/* ERROR: $includeFile not found */";
}
$content = file_get_contents($filePath);
// If escapeType is set, escape the content accordingly
if ($escapeType) {
switch ($escapeType) {
case 'js':
$content = json_encode($content); // JS string literal safe
// optionally trim quotes from json_encode if you want raw string:
// $content = trim($content, '"');
break;
case 'html':
$content = htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
break;
case 'php':
// Escape $ signs for PHP heredoc or double-quoted strings
$content = str_replace('$', '\\$', $content);
break;
case 'shell':
// Escape $ signs for shell script
$content = str_replace('$', '\\$', $content);
break;
// Add more escape types if needed
default:
// Unknown escape, no escaping or you can throw an error here
break;
}
}
return $content;
}, $template);
// Write the result to the output file
if (file_put_contents($outputFile, $processed) === false) {
fwrite(STDERR, "❌ Error: Could not write to $outputFile\n");
exit(1);
}
echo "✅ File built: $outputFile\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment