Last active
June 15, 2018 13:12
-
-
Save Koopzington/45bff1749ccbb1334cb0e9ced5de3908 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* DISCLAIMER: Even though I tried my best to prevent anything bad from happening, | |
* I can't guarantee that your code won't break after using this script on it. | |
* | |
* What does this script do? | |
* It replaces all occurences of $FooBar and $foo_bar with properly camelCased $fooBar. | |
* Replacements also include references to class properties like $this->foo_bar and $this->FooBar | |
* | |
* Note: Function calls are being ignored (for now) | |
* If you find a bug, feel free to comment. | |
**/ | |
$content = file_get_contents($argv[1]); | |
$tokens = token_get_all($content); | |
$toReplace = []; | |
foreach($tokens as $key => $token) { | |
// Check T_VARIABLE ($foo_bar) and T_STRING with preceding T_OBJECT_OPERATOR ($this->foo_bar) | |
if (is_array($token) | |
&& ( | |
$token[0] === 320 // T_VARIABLE | |
|| ( | |
$token[0] === 319 // T_STRING | |
&& $tokens[$key -1][0] === 366 // T_OBJECT_OPERATOR | |
&& $tokens[$key +1] !== '(' // Ignore function calls | |
) | |
) | |
) { | |
$firstLetterPos = strpos($token[1], "$") === 0 ? 1 : 0; | |
$firstLetter = substr($token[1], $firstLetterPos , 1); | |
// Get triggered if you find underscores or if the first letter of the variable name is uppercased | |
if (strpos($token[1], "_") !== false || $firstLetter !== strtolower($firstLetter)) { | |
// Make every letter preceded by an underscore uppercased | |
$proper = ucwords($token[1], '_'); | |
// Remove underscores from token | |
$proper = str_replace("_", "", $proper); | |
// Ensure the first letter is always lowercased | |
$proper = substr_replace($proper, strtolower($firstLetter), $firstLetterPos, 1); | |
// Ensure to only replace the string if it's preceded by an T_OBJECT_OPERATOR | |
if ($tokens[$key -1][0] === 366) { | |
$toReplace['>' . $token[1]] = '>' . $proper; | |
} else { | |
$toReplace[$token[1]] = $proper; | |
} | |
} | |
} | |
} | |
foreach ($toReplace as $find => $replace) { | |
echo $find . ' => ' . $replace . "\t"; | |
if (strpos($content, $replace) === false) { | |
$content = str_replace($find, $replace, $content); | |
} else { | |
echo 'Can\'t safely replace! ' . $replace . ' already found in the code!'; | |
} | |
echo PHP_EOL; | |
} | |
file_put_contents($argv[1], $content); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment