Skip to content

Instantly share code, notes, and snippets.

@SrcFlux
Created October 2, 2015 11:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save SrcFlux/ec1ccb9e917516347e35 to your computer and use it in GitHub Desktop.
Save SrcFlux/ec1ccb9e917516347e35 to your computer and use it in GitHub Desktop.
Get the namespace of a class in Laravel
<?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