Ability to refactor legacy factories to class-based factories (Laravel 8)
Hi!
It will be nice to have ability to refactor legacy model factories to class-based.
Important things:
- Namespace should be found by parsing the composer.json file (psr-4)
- Don't forget states
Before:
<?php
declare(strict_types=1);
use App\Models\User;
use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Factory as EloquentFactory;
/** @var EloquentFactory $factory */
$factory->define(User::class, static function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'phone' => $faker->e164PhoneNumber,
'password' => bcrypt('Pa$$w0rd'),
'locale' => 'en_US',
];
});
$factory->state(User::class, 'someState', [
'foo' => 'bar',
]);
After:
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
protected $model = User::class;
/**
* @return array
*/
public function definition(): array
{
return [
'name' => $this->faker->name,
'email' => $this->faker->safeEmail,
'phone' => $this->faker->e164PhoneNumber,
'password' => bcrypt('Pa$$w0rd'),
'locale' => 'en_US',
];
}
/**
* @return $this
*/
public function someState(): self
{
return $this->state(static function (): array {
return [
'foo' => 'bar',
];
});
}
}
Interesting thing to implement. Maybe better to create a code generation "Convert factories to class factories" where developer can choose which factories to convert... with "add HasFactory" option. As I remember factories can't have any structure, they all should be in the "database/factories" folder without subfolders, right?
Right.
It should be in the "database/factories" and namespace should be detected via PSR4 mapping in the composer.json
https://laravelshift.com/workbench

Too much effort. And there are other tools for that)