60 lines
1.9 KiB
PHP
60 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace Database\Factories;
|
|
|
|
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
|
|
use App\Modules\Machines\Domain\Enums\MachineType;
|
|
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
|
|
use Illuminate\Database\Eloquent\Factories\Factory;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
/**
|
|
* @extends Factory<MachineModel>
|
|
*/
|
|
class MachineFactory extends Factory
|
|
{
|
|
protected $model = MachineModel::class;
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function definition(): array
|
|
{
|
|
return [
|
|
'name' => fake()->unique()->words(2, true),
|
|
'type' => MachineType::Printer,
|
|
'is_active' => true,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param list<int> $serviceUnitIds
|
|
*/
|
|
public function inUnits(array $serviceUnitIds): static
|
|
{
|
|
return $this->afterCreating(function (MachineModel $machine) use ($serviceUnitIds): void {
|
|
// Replaces the default unit that configure() gave the machine first.
|
|
DB::table('machine_service_units')->where('machine_id', $machine->id)->delete();
|
|
DB::table('machine_service_units')->insert(array_map(
|
|
fn (int $unitId): array => ['machine_id' => $machine->id, 'service_unit_id' => $unitId],
|
|
$serviceUnitIds,
|
|
));
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Every machine has a service unit: Painotuotanto (or a new one) unless given.
|
|
*/
|
|
public function configure(): static
|
|
{
|
|
return $this->afterCreating(function (MachineModel $machine): void {
|
|
if (DB::table('machine_service_units')->where('machine_id', $machine->id)->exists()) {
|
|
return;
|
|
}
|
|
|
|
$unitId = ServiceUnitModel::query()->where('name', 'Painotuotanto')->value('id') ?? ServiceUnitModel::factory()->create()->id;
|
|
DB::table('machine_service_units')->insert(['machine_id' => $machine->id, 'service_unit_id' => $unitId]);
|
|
});
|
|
}
|
|
}
|