Skip to content

Instantly share code, notes, and snippets.

@ArielMejiaDev
Forked from SrcFlux/NamespaceHelper.php
Created October 18, 2022 01:05
Show Gist options
  • Save ArielMejiaDev/793d8d7145d5782215e881432fdbe191 to your computer and use it in GitHub Desktop.
Save ArielMejiaDev/793d8d7145d5782215e881432fdbe191 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