Created
December 14, 2011 18:22
-
-
Save weierophinney/1477814 to your computer and use it in GitHub Desktop.
resolveClass from import statements
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
/** | |
* Attempt to resolve a class or namespace based on imports | |
* | |
* @param string $class | |
* @return string String namespace/classname | |
*/ | |
protected function resolveClass($class) | |
{ | |
if ('\\' == substr($class, 0, 1)) { | |
return substr($class, 1); | |
} | |
foreach ($this->getUses() as $import) { | |
// check for an "as". | |
if (isset($import['as'])) { | |
$as = $import['as']; | |
// If it matches $class exactly, use the "use" value provided | |
if ($as == $class) { | |
return $import['use']; | |
} | |
// If the first portion of $class matches, then resolve with | |
// "use\\(classname - as)" | |
$initialSegment = substr($class, 0, (strlen($as) + 1)); | |
if ($as . '\\' == $initialSegment) { | |
return $import['use'] . '\\' . substr($class, (strlen($as) + 1)); | |
} | |
// Otherwise, we know this is not a match | |
continue; | |
} | |
// get final segment of namespace provided in "use" | |
$use = $import['use']; | |
if (false === strstr($use, '\\')) { | |
$finalSegment = $use; | |
} else { | |
$finalSegment = substr($use, strrpos($use, '\\') + 1); | |
} | |
// if class === final segment, return full "use" | |
if ($class == $finalSegment) { | |
return $use; | |
} | |
// if initial segment of class === final segment, return use + (class - initial segment) | |
if (strstr($class, '\\')) { | |
$initialSegment = substr($class, 0, strpos($class, '\\')); | |
if ($finalSegment == $initialSegment) { | |
return $use . '\\' . substr($class, strpos($class, '\\') + 1); | |
} | |
} | |
// Did not match... move to next | |
} | |
// check to see if a class by this name exists in the current namespace | |
// if so, resolve to "namespace\\classname" | |
$resolved = $this->getNamespace() . '\\' . $class; | |
if (class_exists($resolved)) { | |
return $resolved; | |
} | |
// Did not resolve; consider it fully resolved | |
return $class; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment