Created
July 27, 2020 02:09
-
-
Save thephucit/50e5be38f448fed700bb9286838a292d to your computer and use it in GitHub Desktop.
Get namespace from file path
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
<?php | |
/** | |
* Extract namespace from a PHP file | |
* | |
* @param string $file | |
* @return string | |
*/ | |
public function extractNamespace(string $file) : string | |
{ | |
$contents = file_exists($file) ? file_get_contents($file) : $file; | |
$namespace = $class = ''; | |
$getting_namespace = $getting_class = false; | |
foreach (token_get_all($contents) as $token) { | |
if (is_array($token) && $token[0] == T_NAMESPACE) { | |
$getting_namespace = true; | |
} | |
if (is_array($token) && $token[0] == T_CLASS) { | |
$getting_class = true; | |
} | |
// While we're grabbing the namespace name... | |
if ($getting_namespace === true) { | |
if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) { | |
$namespace .= $token[1]; | |
} else if ($token === ';') { | |
$getting_namespace = false; | |
} | |
} | |
if ($getting_class === true) { | |
if (is_array($token) && $token[0] == T_STRING) { | |
$class = $token[1]; | |
break; | |
} | |
} | |
} | |
return $namespace ? $namespace . '\\' . $class : $class; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment