public
Created

Script used to do mass import statement fixes in ZF2

  • Download Gist
replace-uses.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?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";

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.