Skip to content

Instantly share code, notes, and snippets.

@taai
Created October 5, 2022 11:39
Show Gist options
  • Save taai/fac0efe19277581a63282821972f89e7 to your computer and use it in GitHub Desktop.
Save taai/fac0efe19277581a63282821972f89e7 to your computer and use it in GitHub Desktop.
Rename class constructor methods to `__construct`
<?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