Last active
March 19, 2022 20:06
-
-
Save lepikhinb/4856e54b16042ecde2a4c2358a37a787 to your computer and use it in GitHub Desktop.
Laravel 8 Model Factory resolver
This file contains hidden or 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 Tests; | |
use Illuminate\Database\Eloquent\Factories\Factory; | |
use Illuminate\Foundation\Testing\TestCase as BaseTestCase; | |
use Illuminate\Support\Facades\File; | |
use Illuminate\Support\Str; | |
use ReflectionClass; | |
use SplFileInfo; | |
abstract class TestCase extends BaseTestCase | |
{ | |
use CreatesApplication; | |
protected function setUp(): void | |
{ | |
parent::setUp(); | |
$factoryFiles = collect(File::allFiles(database_path('factories'))); | |
Factory::guessFactoryNamesUsing(function ($modelName) use ($factoryFiles) { | |
return $factoryFiles->map(function (SplFileInfo $splFileInfo) { | |
return 'Database\\Factories\\' . | |
str_replace( | |
'/', | |
'\\', | |
Str::between($splFileInfo->getPathName(), database_path('factories/'), '.php') | |
); | |
}) | |
->filter(function (string $className) use ($modelName) { | |
$factory = new $className; | |
$reflection = new ReflectionClass($className); | |
$property = $reflection->getProperty('model'); | |
$property->setAccessible(true); | |
return $property->getValue($factory) === $modelName; | |
}) | |
->first(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment