Skip to content

Instantly share code, notes, and snippets.

@kmuenkel
Last active August 22, 2023 16:28
Show Gist options
  • Save kmuenkel/35999f33f09d8dfad722a63baa90481d to your computer and use it in GitHub Desktop.
Save kmuenkel/35999f33f09d8dfad722a63baa90481d to your computer and use it in GitHub Desktop.
<?php
namespace Database\Seeders;
use Str;
use File;
use SplFileInfo;
use ReflectionClass;
use ReflectionException;
use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
protected array $omit = [];
/**
* Seed the application's database with all files in the same directory as this one.
* @throws ReflectionException
*/
public function run(): void
{
$omit = array_map(fn (string $className) => '\\'.ltrim($className, '\\'), $this->omit);
$omit = array_merge($omit, ['\\'.static::class, '\\'.self::class]);
$namespace = (new ReflectionClass($this))->getNamespaceName();
$seederNames = array_filter(array_map(function (SplFileInfo $fileInfo) use ($namespace, $omit) {
$extension = strtolower($fileInfo->getExtension());
$fileName = Str::beforeLast($fileInfo->getRelativePathname(), ".$extension");
$className = "\\$namespace\\$fileName";
$classInfo = new ReflectionClass($className);
$isAllowed = !in_array($className, $omit);
$isAllowed &= $extension == 'php';
$isAllowed &= !$classInfo->isTrait() && !$classInfo->isAbstract();
return $isAllowed ? $className : null;
}, File::allFiles(__DIR__)));
$this->call($seederNames);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment