Skip to content

Instantly share code, notes, and snippets.

@jokeyrhyme
Created August 11, 2016 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jokeyrhyme/d31390949b467605c2abd5acb7c284ae to your computer and use it in GitHub Desktop.
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
<?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