Skip to content

Instantly share code, notes, and snippets.

@pgl
Forked from nikic/portAlternativeTags.php
Last active August 29, 2015 14:07
Show Gist options
  • Save pgl/e28468339344d0bcd91f to your computer and use it in GitHub Desktop.
Save pgl/e28468339344d0bcd91f to your computer and use it in GitHub Desktop.
<?php
/*
* Note: This script will directly modify the .php files in the given directory.
* It is assumed that the code is under version control, so you can easily review
* the changes using `git diff` or similar.
*/
function usageError() {
die("Usage: php -d asp_tags=1 portAlternativeTags.php dir/\n");
}
if ($argc !== 2) {
usageError();
}
$dir = $argv[1];
if (!is_dir($dir)) {
echo "\"$dir\" is not a directory.\n";
usageError();
}
if (!ini_get('asp_tags')) {
echo "asp_tags must be enabled.\n";
usageError();
}
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($it as $file) {
if (!preg_match('/\.php$/', $file)) {
continue;
}
$code = file_get_contents($file);
$tokens = token_get_all($code);
$tokens = portTags($tokens);
$code = tokensToCode($tokens);
file_put_contents($file, $code);
}
function portTags(array $tokens) {
foreach ($tokens as $i => &$token) {
if ($token[0] === T_OPEN_TAG) {
if (strpos($token[1], '<?') === 0) {
continue;
}
$token[1] = '<?php';
if (!isset($tokens[$i]) || $tokens[$i][0] !== T_WHITESPACE) {
$token[1] .= ' ';
}
} else if ($token[0] === T_OPEN_TAG_WITH_ECHO) {
if ($token[1] === '<?=') {
continue;
}
$token[1] = '<?=';
} else if ($token[0] === T_CLOSE_TAG) {
if (strpos($token[1], '?>') === 0) {
continue;
}
if (preg_match('~^(?:%>|</script\s*>)(\s*)$~'i, $token[1], $matches)) {
$token[1] = '?>' . $matches[1];
}
}
}
return $tokens;
}
function tokensToCode(array $tokens) {
$code = '';
foreach ($tokens as $token) {
if (is_array($token)) {
$code .= $token[1];
} else {
$code .= $token;
}
}
return $code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment