Created
October 5, 2022 11:39
-
-
Save taai/fac0efe19277581a63282821972f89e7 to your computer and use it in GitHub Desktop.
Rename class constructor methods to `__construct`
This file contains hidden or 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
<?php | |
// dry run | |
// find . -type f -name '*.php' -exec php fix-constructors.php {} \; | |
// real run | |
// find . -type f -name '*.php' -exec php fix-constructors.php {} y \; | |
// @read https://ideone.com/aLpfBh | |
// @read https://regex101.com/r/hzzzkz/1/ | |
$filepath = $argv[1]; | |
$dryRun = empty($argv[2]); | |
$source = file_get_contents($filepath); | |
$class_regex = '~ | |
^\s*class\s+ | |
(?P<class>\S+)[^{}]+(\{ | |
(?:[^{}]*|(?2))* | |
\})~mx'; | |
$result = preg_replace_callback( | |
$class_regex, | |
function ($match) { | |
$function_regex = '~function\s+\K'.$match['class'].'~'; | |
return preg_replace($function_regex, '__construct', $match[0]); | |
}, | |
$source | |
); | |
if ($result && $result !== $source) { | |
echo "File '{$filepath}' needs a fix.\n"; | |
if (!$dryRun) { | |
if (!file_put_contents($filepath, $result)) { | |
fwrite(STDERR, "Failed to rewrite the file '{$filepath}'.\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment