Skip to content

Instantly share code, notes, and snippets.

@shevron
Created August 12, 2012 10:45
Show Gist options
  • Save shevron/3331180 to your computer and use it in GitHub Desktop.
Save shevron/3331180 to your computer and use it in GitHub Desktop.
Convert single, comma separated mutli-namspace use statements into multiple use calls with single namespace references
<?php
/**
* Convert single use calls with comma separated list of namespaces into
* multiple, stand-alone use calls
*
* Usage: php cs-fix-use.php <file>
*
* Will overwrite <file> with new version. If <file> is omitted, stdin / stdout
* will be used.
*
* To run on an entire directory, it is recommended to use a tool such as find,
* for example:
*
* find ./src -type f -name "*.php" -exec php cs-fix-use.php {}\;
*
* NOTE: you should back up your code or make sure it is committed to SCM before
* using this script. This may break your code.
*
*/
if (PHP_SAPI != 'cli') {
echo "Sorry, this script should be run in CLI\n";
exit(1);
}
if (isset($_SERVER['argv'][1])) {
$file = $_SERVER['argv'][1];
} else {
$file = 'php://stdin';
}
$input = file_get_contents($file);
if (! $input) {
fprintf(STDERR, "ERROR: unable to read input file $file\n");
exit(1);
}
// Step 1: find all use statements
if (preg_match_all('/^use\s+([^;]+,[^;]+)/ms', $input, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
// Step 2: break down statement into specific use calls
$statements = explode(',', $match[1]);
foreach($statements as $key => $value) {
$value = trim($value);
$statements[$key] = "use $value";
}
// Step 3: Replace use block
$replacement = implode(";\n", $statements);
$input = str_replace($match[0], $replacement, $input);
}
}
// Write output back
if ($file == 'php://stdin') {
// print to stdout
echo $input;
} else {
// Write back to the original file
file_put_contents($file, $input);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment