Last active
August 22, 2023 16:28
-
-
Save kmuenkel/35999f33f09d8dfad722a63baa90481d to your computer and use it in GitHub Desktop.
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 | |
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