|
<?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*)$~', $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; |
|
} |
Hi,
Am I right in saying that this script won't work in PHP7? Since it relies on ASP tags being enabled?
How strange... by definition this script will be used by people who have migrated to PHP7 and want to "fix" old scripts...
Am I missing something?
Cheers!