Created
January 28, 2020 19:08
-
-
Save kmuenkel/9b10d7cfe5a6740664e543991e0379ae to your computer and use it in GitHub Desktop.
Laravel Helper function for loading all classes in a given directory
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 | |
if (!function_exists('load')) { | |
/** | |
* Register all of the commands in the given directory. | |
* | |
* @param array|string $paths | |
* @param string $parentClassName | |
* @param callable|null $register | |
* @see Illuminate\Foundation\Console\Kernel::load() | |
*/ | |
function load($paths, $parentClassName = null, callable $register = null) | |
{ | |
$paths = array_unique(Arr::wrap($paths)); | |
$paths = array_filter($paths, function ($path) { | |
return is_dir($path); | |
}); | |
if (empty($paths)) { | |
return; | |
} | |
$namespace = app()->getNamespace(); | |
/** @var SplFileInfo $fileInfo */ | |
foreach ((new Finder)->in($paths)->files() as $fileInfo) { | |
$className = $namespace.str_replace( | |
['/', '.php'], | |
['\\', ''], | |
Str::after($fileInfo->getPathname(), realpath(app_path()).DIRECTORY_SEPARATOR) | |
); | |
if ((!$parentClassName || is_subclass_of($className, $parentClassName)) && | |
!app(ReflectionClass::class, ['argument' => $className])->isAbstract() | |
) { | |
$class = app($className); | |
$register && $register($class); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment