plugin icon indicating copy to clipboard operation
plugin copied to clipboard

Ability to refactor legacy factories to class-based factories (Laravel 8)

Open zlodes opened this issue 4 years ago • 3 comments

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',
			];
		});
    }
}

zlodes avatar Feb 15 '21 17:02 zlodes

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?

adelf avatar Feb 15 '21 18:02 adelf

Right.

It should be in the "database/factories" and namespace should be detected via PSR4 mapping in the composer.json

zlodes avatar Feb 16 '21 13:02 zlodes

https://laravelshift.com/workbench

image

CrazyBoy49z avatar Oct 28 '21 16:10 CrazyBoy49z

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

adelf avatar Dec 23 '23 20:12 adelf