Skip to content

Instantly share code, notes, and snippets.

@weierophinney
Created July 9, 2012 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weierophinney/3079222 to your computer and use it in GitHub Desktop.
Save weierophinney/3079222 to your computer and use it in GitHub Desktop.
Script used to do mass import statement fixes in ZF2
<?php
echo "Analyzing {$argv[1]}\n";
$file = file_get_contents($argv[1]);
$matches = null;
preg_match('/\n(use .*?)(?:\r?\n(?:\/\*|interface|abstract|class|trait))/s', $file, $matches);
if (!$matches || !$matches[1]) {
echo " Did not match initial pattern\n";
exit(0);
}
// echo " Matches: " . var_export($matches, 1) . "\n";
$matched = "\n" . $matches[1];
$uses = array();
preg_replace_callback(
'/\n(?:use\s+|\s*)([a-zA-Z][a-zA-Z0-9\\\\_]*( as [a-zA-Z0-9_]+)?)/',
function ($m) use (&$uses) {
// echo "Callback matches: " . var_export($m, 1) . "\n\n";
$uses[] = $m[1];
},
$matched
);
natcasesort($uses);
$uses = "\nuse " . implode(";\nuse ", $uses) . ";\n";
$replaced = str_replace($matched, $uses, $file);
file_put_contents($argv[1], $replaced);
echo " Wrote changes\n";
@weierophinney
Copy link
Author

To execute, I did the following from the library/Zend directory, using zsh:

for file in **/*;do
    php /path/to/replace-uses.php $file;
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment