Last active
February 15, 2021 21:53
-
-
Save BenMorel/6994483 to your computer and use it in GitHub Desktop.
Replaces traditional array() syntax with the short syntax []
This file contains 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
#!/usr/bin/env php | |
<?php | |
/** | |
* Converts all PHP files in a directory to short array syntax. | |
* Note that this will overwrite all converted PHP files. | |
* Be sure to have a backup just in case. | |
*/ | |
if ($argc !== 2) { | |
printf('Usage: %s src-dir' . PHP_EOL, $argv[0]); | |
exit(1); | |
} | |
$dir = $argv[1]; | |
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); | |
foreach ($files as $file) { | |
/** @var SplFileInfo $file */ | |
if ($file->isFile()) { | |
if (pathinfo($file->getFilename(), PATHINFO_EXTENSION) === 'php') { | |
$original = file_get_contents($file->getPathname()); | |
$modified = convertToShortArraySyntax($original); | |
if ($modified !== $original) { | |
echo "Converted {$file->getPathname()}\n"; | |
file_put_contents($file->getPathname(), $modified); | |
} | |
} | |
} | |
} | |
function convertToShortArraySyntax(string $php): string | |
{ | |
$tokens = token_get_all($php); | |
$output = ''; | |
$bracketStack = []; | |
$replaceNextParentheses = false; | |
for ($i = 0; isset($tokens[$i]); $i++) { | |
$token = $tokens[$i]; | |
if (is_array($token)) { | |
if ($token[0] == T_ARRAY) { | |
for ($j = $i + 1; isset($tokens[$j]); $j++) { | |
$peekToken = $tokens[$j]; | |
if (is_array($peekToken)) { | |
if ($peekToken[0] == T_WHITESPACE) { | |
continue; | |
} | |
if ($peekToken[1] == '(') { | |
$replaceNextParentheses = true; | |
continue 2; | |
} | |
} | |
elseif ($peekToken == '(') { | |
$replaceNextParentheses = true; | |
continue 2; | |
} | |
break; | |
} | |
} | |
$output .= $token[1]; | |
} else { | |
if ($token == '(') { | |
$openingBracket = $replaceNextParentheses ? '[' : '('; | |
$closingBracket = $replaceNextParentheses ? ']' : ')'; | |
$output .= $openingBracket; | |
array_push($bracketStack, $closingBracket); | |
$replaceNextParentheses = false; | |
} | |
elseif ($token == ')') { | |
$output .= array_pop($bracketStack); | |
} else { | |
$output .= $token; | |
} | |
} | |
} | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
interest ?