Skip to content

Instantly share code, notes, and snippets.

@derak-kilgo
Last active August 29, 2015 14:06
Show Gist options
  • Save derak-kilgo/041662a29cd614e75f43 to your computer and use it in GitHub Desktop.
Save derak-kilgo/041662a29cd614e75f43 to your computer and use it in GitHub Desktop.
Extract classnames from a php file.
<?php
Class LegacyAutoloader
{
/**
* Tokenize a php file and extract all classes defined inside.
* @param $filePath
* @return array
*/
public static function extractClasses($filePath){
$classNames = array();
$tokens = token_get_all(file_get_contents($filePath));
$intTokens = count($tokens);
$pos = 0;
while($pos < $intTokens){
if($tokens[$pos][0] == T_CLASS){
$classNames[] = $tokens[$pos+2][1];
}
$pos++;
}
//var_dump($classNames);
return $classNames;
}
/**
* Walk a directory and extract Classes from each php file.
*/
public static function mapClassesRecursive($baseFolder){
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseFolder), RecursiveIteratorIterator::SELF_FIRST);
$classMap = array();
foreach($it as $fileInfo){
if(!$fileInfo->isDir()){
$classes = self::extractClasses($fileInfo->getRealPath());
foreach($classes as $class){
$classMap[$class] = $fileInfo->getRealPath();
}
}
}
return $classMap;
}
}
//sample usage
//LegacyAutoloader::mapClassesRecursive('/var/www/html/lib');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment