Skip to content

Instantly share code, notes, and snippets.

@mertenvg
Created December 14, 2012 19:54
Show Gist options
  • Save mertenvg/4288127 to your computer and use it in GitHub Desktop.
Save mertenvg/4288127 to your computer and use it in GitHub Desktop.
Extract a fully qualfied (namespaced) classname from a php file. This function assumes PSR-0 compliance.
/**
* Extract a fully qualfied (namespaced) classname from a php file.
* This function assumes PSR-0 compliance.
*
* @param string $filePath Path to the php file.
* @return string|false The resulting classname
*/
function extractFullClassNameFromFile($filePath)
{
if (!file_exists($filePath)) {
return false;
}
$namespace = null;
$classname = null;
$cnMatches = null;
$nsMatches = null;
$file = file_get_contents($filePath);
if (preg_match_all('/\n\s*(abstract\s|final\s)*class\s+(?<name>[^\s;]+)\s*/i', $file, $cnMatches, PREG_PATTERN_ORDER)) {
$classname = array_pop($cnMatches['name']);
if (preg_match_all('/namespace\s+(?<name>[^\s;]+)\s*;/i', $file, $nsMatches, PREG_PATTERN_ORDER)) {
$namespace = array_pop($nsMatches['name']);
}
}
if (empty($classname)) {
return false;
}
return "$namespace\\$classname";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment