-
-
Save ArielMejiaDev/793d8d7145d5782215e881432fdbe191 to your computer and use it in GitHub Desktop.
Get the namespace of a class in Laravel
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 | |
namespace App\Helpers; | |
class NamespaceHelper | |
{ | |
/** | |
* Get the namespace of a class. | |
* | |
* @param string $className | |
* @param string $searchPath | |
* @return string | |
*/ | |
public static function getNamespace($className, $searchPath = '/') | |
{ | |
$recursiveDirectoryIterator = new \RecursiveDirectoryIterator(app_path($searchPath)); | |
$recursiveIteratorIterator = new \RecursiveIteratorIterator($recursiveDirectoryIterator); | |
$regexIterator = new \RegexIterator($recursiveIteratorIterator, '/' . $className . '\.php/', \RegexIterator::GET_MATCH); | |
$iteratorArray = iterator_to_array($regexIterator); | |
$classPath = key($iteratorArray); | |
$namespace = str_replace([app_path('\\'), '.php'], null, $classPath); | |
return $namespace; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment