Skip to content

Instantly share code, notes, and snippets.

@lucenarenato
Forked from SrcFlux/NamespaceHelper.php
Created November 1, 2022 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucenarenato/2fa135cd13d009ad57500962daff0c58 to your computer and use it in GitHub Desktop.
Save lucenarenato/2fa135cd13d009ad57500962daff0c58 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