ldc-legaulois/database/factories/OrderFactory.php
2026-09-28 10:51:17 +02:00

95 lines
3.1 KiB
PHP

<?php
namespace Database\Factories;
use App\Enums\Shop\ContactFormCivility;
use App\Enums\Shop\OrderStatus;
use App\Enums\Shop\OrderType;
use App\Models\Customer;
use App\Models\Order;
use App\Models\SellItem;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Order>
*/
class OrderFactory extends Factory
{
protected $model = Order::class;
#[\Override]
protected function withFaker()
{
return class_exists(\Faker\Generator::class) ? parent::withFaker() : null;
}
public function definition(): array
{
return $this->faker !== null
? $this->definitionWithFaker()
: $this->definitionStatic();
}
/**
* @return array<string, mixed>
*/
private function definitionWithFaker(): array
{
return [
'ref' => strtoupper(Str::random(10)),
'firstname' => fake()->firstName(),
'lastname' => fake()->lastName(),
'address' => fake()->streetAddress(),
'postcode' => fake()->postcode(),
'phone' => fake()->optional()->phoneNumber(),
'email' => fake()->safeEmail(),
'city' => fake()->city(),
'civility' => fake()->randomElement(ContactFormCivility::cases()),
'status' => fake()->randomElement(OrderStatus::cases()),
'payementType' => fake()->randomElement(OrderType::cases()),
'confirmMailSent' => fake()->boolean(20),
'customer_id' => Customer::factory(),
];
}
/**
* @return array<string, mixed>
*/
private function definitionStatic(): array
{
return [
'ref' => 'CMD-TEST-12345',
'firstname' => 'Alexandre',
'lastname' => 'Dupont',
'address' => '123 Rue de la République',
'postcode' => '75001',
'phone' => '0102030405',
'email' => 'client.test@exemple.org',
'city' => 'Paris',
'civility' => ContactFormCivility::m,
'status' => OrderStatus::waitingCheck,
'payementType' => OrderType::check,
'confirmMailSent' => true,
'customer_id' => 1,
];
}
public function withSellItems(int $count = 3, int $quantityMin = 1, int $quantityMax = 5): static
{
return $this->afterCreating(function (Order $order) use ($count, $quantityMin, $quantityMax) {
$items = SellItem::factory()->count($count)->create();
$pivotData = $items->mapWithKeys(function (SellItem $item) use ($quantityMin, $quantityMax) {
$quantity = $this->faker !== null
? fake()->numberBetween($quantityMin, $quantityMax)
: 1;
return [$item->id => ['quantity' => $quantity]];
})->all();
$order->sellItems()->attach($pivotData);
});
}
}