ldc-arcadia-api/database/arcadia-replicate/Factories/AbstractTableFactory.php

88 lines
2.2 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace Database\ArcadiaReplicate\Factories;
use Illuminate\Support\Facades\DB;
abstract class AbstractTableFactory implements TableFactory
{
/** @var list<callable(array<string, mixed>): array<string, mixed>|array<string, mixed>> */
protected array $states = [];
public function __construct(
protected string $connection
) {
}
public static function new(string $connection): static
{
return new static($connection);
}
/**
* @param callable(array<string, mixed>): array<string, mixed>|array<string, mixed> $state
*/
public function state(callable | array $state): static
{
$clone = clone $this;
$clone->states[] = $state;
return $clone;
}
/**
* Génère le tableau de données avec les states et surcharges appliqués.
*
* @param array<string, mixed> $attributes
* @return array<string, mixed>
*/
public function raw(array $attributes = []): array
{
$data = $this->definition();
foreach ($this->states as $state) {
$stateData = is_callable($state) ? $state($data) : $state;
$data = array_merge($data, $stateData);
}
return array_merge($data, $attributes);
}
/**
* Insère un enregistrement dans la base Oracle répliquée et retourne le tableau inséré.
*
* @param array<string, mixed> $attributes
* @return array<string, mixed>
*/
public function create(array $attributes = []): array
{
$data = $this->raw($attributes);
$tableName = static::table()::name();
DB::connection($this->connection)
->table($tableName)
->insert($data);
return $data;
}
/**
* Insère N enregistrements dans la table.
*
* @param array<string, mixed> $attributes
* @return list<array<string, mixed>>
*/
public function createMany(int $count, array $attributes = []): array
{
$rows = [];
for ($i = 0; $i < $count; $i++) {
$rows[] = $this->create($attributes);
}
return $rows;
}
}