-
-
Save lapistano/1451137 to your computer and use it in GitHub Desktop.
Script to clean unnecessary PHP use statements
This file contains 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
#!/usr/bin/env php | |
<?php | |
$paths = array(); | |
if (isset($_SERVER['argv'])) | |
{ | |
$paths = $_SERVER['argv']; | |
array_shift($paths); | |
if (!$paths) | |
{ | |
$paths[] = '.'; | |
} | |
} | |
foreach ($paths as $path) | |
{ | |
if (!$realpath = realpath($path)) throw new Exception("Unable to resolve path '".$path."'."); | |
cleanUse($realpath); | |
} | |
function cleanUse($path) | |
{ | |
if (is_dir($path)) | |
{ | |
foreach (glob($path.DIRECTORY_SEPARATOR.'*') as $subPath) | |
{ | |
cleanUse($subPath); | |
} | |
return; | |
} | |
echo "Cleaning '".$path."'".PHP_EOL; | |
$content = file_get_contents($path); | |
if ('<?php' != substr($content, 0, 5)) return; | |
if (!preg_match_all('/^use (?<name>.*?)(?:as (?<alias>.*))?;$/m', $content, $matches, PREG_OFFSET_CAPTURE)) return; | |
$useNames = array(); | |
foreach ($matches['name'] as $matchNumber => $match) | |
{ | |
$name = explode('\\', $match[0]); | |
$useNames[$matchNumber] = array_pop($name); | |
} | |
foreach ($matches['alias'] as $matchNumber => $match) | |
{ | |
if (!$match || !$match[0]) continue; | |
$useNames[$matchNumber] = $match[0]; | |
} | |
$lastMatch = $matches[0][count($matches[0]) - 1]; | |
$offset = $lastMatch[1] + strlen($lastMatch[0]); | |
$unusedNames = array(); | |
foreach ($useNames as $useName) | |
{ | |
if (preg_match('/\b'.preg_quote($useName, '/').'\b/', $content, $matches, null, $offset)) continue; | |
$unusedNames[] = $useName; | |
} | |
if (!$unusedNames) return; | |
echo "Found unused 'use'(s) in '".$path."':".PHP_EOL; | |
foreach ($unusedNames as $unusedName) | |
{ | |
echo " - '".$unusedName."'".PHP_EOL; | |
} | |
echo 'Removing...'; | |
foreach ($unusedNames as $unusedName) | |
{ | |
$content = preg_replace('/^use .*'.preg_quote($unusedName, '/').';$\s/m', '', $content); | |
} | |
file_put_contents($path, $content); | |
echo 'done.'.PHP_EOL; | |
} |
Author
lapistano
commented
Feb 3, 2012
via email
Hoi,
nope, sry.
Hab das script dazumal auch von ezzatron übernommen und weder gebraucht,
noch angeschaut. Sry.
hf
Basti
…On 02/03/2012 09:59 AM, Volker Dusch wrote:
You don't happen to have that as a phpcs/phpmd rule do you? :)
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/1451137
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment