Created
August 11, 2016 03:09
-
-
Save jokeyrhyme/d31390949b467605c2abd5acb7c284ae to your computer and use it in GitHub Desktop.
quick and bad script to migrate PHP heredoc out into a separate file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
usage: | |
php extract-heredoc.php my-code-file.php | |
creates my-code-file.heredoc.php | |
assumes input file is a single <?php code block | |
manual correction of super-global usage is needed | |
e.g. $_POST, $_REQUEST, etc | |
highly-recommended that changes be human-vetted | |
*/ | |
if ($argc < 2) { | |
echo 'not enough arguments'; | |
exit(1); | |
} | |
$inputPath = realpath($argv[1]); | |
if (preg_match('|\.php$|', $inputPath) !== 1) { | |
echo 'filename must end with ".php"'; | |
exit(1); | |
} | |
$heredocFilename = basename($inputPath, '.php') . '.heredoc.php'; | |
$heredocPath = dirname($inputPath) . '/' . $heredocFilename; | |
$input = file_get_contents($inputPath); | |
$output = preg_replace('|<\?php\n|', "<?php\n\ninclude '$heredocFilename';\n", $input); | |
$heredocs = '<?php' . PHP_EOL . PHP_EOL; | |
function generateName ($content) { | |
return 'heredoc_' . substr(hash('sha256', $content), 0, 7); | |
} | |
$output = preg_replace_callback( | |
'|<<<(\w+).*(\1);|msU', | |
function ($matches) { | |
global $heredocs; | |
$paramsFound = array(); | |
preg_match_all('|[^\\\](\$\w+)|', $matches[0], $paramsFound); | |
$params = array_unique($paramsFound[1]); | |
$name = generateName($matches[0]); | |
$heredocs .= "function $name (" . implode(', ', $params) . ') {' . PHP_EOL; | |
$heredocs .= 'return ' . $matches[0] . PHP_EOL; | |
$heredocs .= '}' . PHP_EOL . PHP_EOL; | |
return $name . '(' . implode(', ', $params) . ');'; | |
}, | |
$output | |
); | |
file_put_contents($inputPath, $output); | |
file_put_contents($heredocPath, $heredocs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment