Skip to content

Instantly share code, notes, and snippets.

@lapistano
Forked from ezzatron/clean-use.php
Created December 9, 2011 11:11
Show Gist options
  • Select an option

  • Save lapistano/1451137 to your computer and use it in GitHub Desktop.

Select an option

Save lapistano/1451137 to your computer and use it in GitHub Desktop.
Script to clean unnecessary PHP use statements
#!/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;
}
@edorian

edorian commented Feb 3, 2012

Copy link
Copy Markdown

You don't happen to have that as a phpcs/phpmd rule do you? :)

@lapistano

lapistano commented Feb 3, 2012 via email

Copy link
Copy Markdown
Author

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