Skip to content

Instantly share code, notes, and snippets.

@artpi
Created January 23, 2018 08:39
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 artpi/e5459d21daced1a38bd98d5ad8a62fb2 to your computer and use it in GitHub Desktop.
Save artpi/e5459d21daced1a38bd98d5ad8a62fb2 to your computer and use it in GitHub Desktop.
Find unused PHP functions
#!/usr/local/bin/php
<?php
function get_funcs( $dir ) {
if ( is_dir( $dir ) ) {
$files = scandir( $dir );
$funcs = array();
foreach ( $files as $file ) {
if ( substr( $file, 0, 1 ) !== '.' ) {
$funcs = array_merge( $funcs, get_funcs( $dir . "/" . $file ) );
}
}
return $funcs;
} else if( stristr( $dir, '.php' ) ) {
// Assuming php file. Lets get functions !
$text = file_get_contents( $dir );
preg_match_all( '#\s*?function\s+([a-zA-Z0-9_]+)\s*?\(#is', $text, $res );
return $res[1];
}
return array();
}
$funcs = array_unique( get_funcs( getcwd() ) );
$blacklist = array(
'log',
'document',
'input',
'callback',
'__construct',
'initialize',
'json_encode',
'output',
'process',
'init',
'add',
'serve',
);
foreach ($funcs as $name ) {
$out = array();
if( in_array( $name, $blacklist ) ) {
continue;
}
//echo "$name:";
try {
exec( "ag --ignore box '[\s=>:]$name\s*?\(' /Users/artpi/GIT/sandbox", $out, $ret );
} catch ( Exception $e ) {
continue;
}
//echo "[".count($out)."] ";
if( count( $out ) < 5 ) {
$used = array_filter( $out, function( $el ) {
return ! stristr( $el, 'function' );
} );
if( count( $used ) === 0 ) {
//echo "unused";
echo $name. "\n";
}
}
//echo "\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment