Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Created January 28, 2020 19:08
Show Gist options
  • Save kmuenkel/9b10d7cfe5a6740664e543991e0379ae to your computer and use it in GitHub Desktop.
Save kmuenkel/9b10d7cfe5a6740664e543991e0379ae to your computer and use it in GitHub Desktop.
Laravel Helper function for loading all classes in a given directory
<?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