ldc-ovoteam/database/seeders/Mandatory/ImportRecipesCsvSeeder.php
Jérémy Munsch 7c80ac1f11
refactor(seeders): simplify product synchronization logic
Replaced conditional with a more concise when() function for syncing products.
2026-10-20 15:39:00 +02:00

344 lines
11 KiB
PHP

<?php
declare(strict_types=1);
namespace Database\Seeders\Mandatory;
use App\Models\Product;
use App\Models\Recipe;
use Domain\Models\ValueObjects\Products\ProductCategory;
use Domain\Models\ValueObjects\Recipes\ConsumptionTime;
use Domain\Models\ValueObjects\Recipes\Inspiration;
use Domain\Models\ValueObjects\Recipes\Season;
use Illuminate\Database\Seeder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
class ImportRecipesCsvSeeder extends Seeder
{
public static string $table = 'recipes';
public const string COL_SEO_TITLE = 'TITRE SEO DE LA PAGE*';
public const string COL_SEO_DESCRIPTION = 'DESCRIPTION SEO DE LA PAGE*';
public const string COL_PICTURE = 'IMAGE/VISUEL*';
public const string COL_PICTURE_ALT = 'ATTRIBUT ALT IMAGE*';
public const string COL_PICTURE_TITLE = 'ATTRIBUT TITLE IMAGE*';
public const string COL_NAME = 'NOM DE LA RECETTE*';
public const string COL_PRODUCT_CATEGORY = 'Gamme associée';
public const string COL_CONSUMPTION_TIME = 'MOMENT DE CONSOMMATION*';
public const string COL_INSPIRATION = 'INSPIRATION*';
public const string COL_SEASON = 'SAISON*';
public const string COL_DESCRIPTION = 'TEXTE/DESCRIPTION*';
public const string COL_DETAILS = 'DÉTAILS*';
public const string COL_INGREDIENTS = 'INGRÉDIENT(S)*';
public const string COL_PREPARATION_STEPS = 'ÉTAPES DE PRÉPARATION*';
public const string COL_TIPS_AND_ADVICES = 'ASTUCES ET CONSEILS';
public const string COL_ASSOCIATED_PRODUCT = 'PRODUIT ASSOCIÉ*';
/**
* @var array<string>
*/
private const array EXPECTED_COLUMNS = [
self::COL_SEO_TITLE,
self::COL_SEO_DESCRIPTION,
self::COL_PICTURE,
self::COL_PICTURE_ALT,
self::COL_PICTURE_TITLE,
self::COL_NAME,
self::COL_PRODUCT_CATEGORY,
self::COL_CONSUMPTION_TIME,
self::COL_INSPIRATION,
self::COL_SEASON,
self::COL_DESCRIPTION,
self::COL_DETAILS,
self::COL_INGREDIENTS,
self::COL_PREPARATION_STEPS,
self::COL_TIPS_AND_ADVICES,
self::COL_ASSOCIATED_PRODUCT,
];
/** @var array<string, int> */
private array $columnMap = [];
public function run(): void
{
DB::transaction(function () {
$filePathName = database_path('seeders/data/recipes.csv');
$resource = new \SplFileObject($filePathName, 'r');
$resource->setCsvControl(';', '"', '\\');
$headerRow = $resource->fgetcsv();
// Skip explanations row
$resource->fgetcsv();
if (! is_array($headerRow)) {
throw new \UnexpectedValueException("Le fichier CSV 'recipes.csv' est vide ou illisible.");
}
$this->validateAndMapHeaders($headerRow);
while (! $resource->eof()) {
$line = $resource->fgetcsv();
if ($line === false || ($line[0] ?? null) === null) {
continue;
}
$this->createAndPersistRecipeFrom($line);
}
(new ImportProductsCsvSeeder())->syncAllAssociatedRecipes();
});
}
/** @param array<array-key, mixed> $line */
private function createAndPersistRecipeFrom(array $line): void
{
$paddedRow = array_pad($line, count($this->columnMap), '');
$samplePicture = new \SplFileInfo(__DIR__ . '/../data/800x800.png');
$recipeName = $this->extractRecipeName($paddedRow, self::COL_NAME)->value();
$seoTitle = $this->strOf($paddedRow, self::COL_SEO_TITLE)->value();
$seoDescription = $this->strOf($paddedRow, self::COL_SEO_DESCRIPTION)->value();
$pictureAlt = Str::limit($recipeName ?? '', 75, '');
$pictureTitle = Str::limit($recipeName ?? '', 75, '');
$productCategory = $this->getEnumValueByLabel(
ProductCategory::class,
$this->strOf($paddedRow, self::COL_PRODUCT_CATEGORY)
);
$consumptionTime = $this->getEnumValueByLabel(
ConsumptionTime::class,
$this->strOf($paddedRow, self::COL_CONSUMPTION_TIME)
);
$inspiration = $this->getEnumValueByLabel(
Inspiration::class,
$this->strOf($paddedRow, self::COL_INSPIRATION)
);
$season = $this->getEnumValueByLabel(
Season::class,
$this->strOf($paddedRow, self::COL_SEASON)
);
$description = when(
$this->hasColumn($paddedRow, self::COL_DESCRIPTION),
fn () => $this->cleanWysiwygOf($paddedRow, self::COL_DESCRIPTION)?->value()
);
$details = when(
$this->hasColumn($paddedRow, self::COL_DETAILS),
fn () => $this->cleanWysiwygOf($paddedRow, self::COL_DETAILS)?->value()
);
$ingredientsList = when(
$this->hasColumn($paddedRow, self::COL_INGREDIENTS),
fn () => $this->cleanWysiwygOf($paddedRow, self::COL_INGREDIENTS)?->value()
);
$preparationSteps = when(
$this->hasColumn($paddedRow, self::COL_PREPARATION_STEPS),
fn () => $this->cleanWysiwygOf($paddedRow, self::COL_PREPARATION_STEPS)?->value()
);
$tipsAndAdvices = when(
$this->hasColumn($paddedRow, self::COL_TIPS_AND_ADVICES),
fn () => $this->cleanWysiwygOf($paddedRow, self::COL_TIPS_AND_ADVICES)?->value()
);
$fillable = [
'seo_title' => $seoTitle,
'seo_description' => $seoDescription,
'picture' => $samplePicture,
'picture_alt' => $pictureAlt,
'picture_title' => $pictureTitle,
'name' => $recipeName,
'product_category' => $productCategory,
'consomption_time' => $consumptionTime,
'inspiration' => $inspiration,
'season' => $season,
'description' => $description,
'details' => $details,
'ingredients_list' => $ingredientsList,
'preparation_steps' => $preparationSteps,
'tips_and_advices' => $tipsAndAdvices,
];
$recipe = Recipe::query()->create($fillable);
$associatedProductName = when(
$this->hasColumn($paddedRow, self::COL_ASSOCIATED_PRODUCT),
fn () => $this->cleanStringOf($paddedRow, self::COL_ASSOCIATED_PRODUCT)?->value()
);
if ($associatedProductName !== null) {
$product = Product::query()
->where('slug', Str::slug($associatedProductName))
->first();
when(
$product !== null,
fn () => $recipe->products()->syncWithoutDetaching([$product->id])
);
}
}
/**
* @param array<int, mixed> $headerRow
*
* @throws \UnexpectedValueException
*/
private function validateAndMapHeaders(array $headerRow): void
{
$columnMap = [];
foreach ($headerRow as $index => $header) {
$headerStr = Arr::string($headerRow, $index);
$cleanHeader = (string) Str::of($headerStr)->replaceMatches('/^\xEF\xBB\xBF/', '')->trim();
if ($cleanHeader !== '') {
$columnMap[$cleanHeader] = $index;
}
}
foreach (self::EXPECTED_COLUMNS as $expectedColumn) {
if (! isset($columnMap[$expectedColumn])) {
throw new \UnexpectedValueException("Colonne d'en-tête manquante ou invalide dans recipes.csv: '{$expectedColumn}'.");
}
}
$this->columnMap = $columnMap;
}
private function getColumnIndex(string $column): int
{
if (! isset($this->columnMap[$column])) {
throw new \InvalidArgumentException("Colonne inconnue : '{$column}'.");
}
return $this->columnMap[$column];
}
/** @param array<array-key, mixed> $arr */
private function hasColumn(array $arr, string $column): bool
{
return array_key_exists($this->getColumnIndex($column), $arr);
}
/**
* @param array<array-key, mixed> $paddedRow
*/
private function extractRecipeName(array $paddedRow, string $column, bool $appendUniqueId = false): Stringable
{
$recipeName = when(
$this->hasColumn($paddedRow, $column),
fn () => $this->cleanStringOf($paddedRow, $column)
);
if ($recipeName === null || $recipeName->isEmpty()) {
throw new \UnexpectedValueException('Recipe name cannot be empty.' . json_encode($paddedRow));
}
if ($appendUniqueId) {
$recipeName = $recipeName->append(' ' . uniqid());
}
return when(
Recipe::query()->where('name', $recipeName->value())->exists(),
fn () => $this->extractRecipeName($paddedRow, $column, true),
$recipeName
);
}
/**
* Retourne une instance de Stringable pour la colonne donnée dans le tableau.
*
* @param array<array-key, mixed> $arr
*/
private function strOf(array $arr, string $column): Stringable
{
return Str::of(Arr::string($arr, $this->getColumnIndex($column)));
}
/** @param array<array-key, mixed> $arr */
private function cleanStringOf(array $arr, string $column): ?Stringable
{
$value = $this->strOf($arr, $column);
return $value->trim()->isEmpty() ? null : $value->trim();
}
/** @param array<array-key, mixed> $arr */
private function cleanWysiwygOf(array $arr, string $column): ?Stringable
{
$cleaned = $this->cleanStringOf($arr, $column);
if ($cleaned === null) {
return null;
}
return Str::of(nl2br($cleaned->toString()));
}
/** @param class-string<\BackedEnum> $enumClass */
private function getEnumValueByLabel(string $enumClass, Stringable $label): ?\BackedEnum
{
$label = $label->trim();
if ($label->isEmpty()) {
throw new \UnexpectedValueException(
"label is required for enum '{$enumClass}'"
);
}
$label = $this->applyLabelMappings($label);
/** @var array<string, string> $labelsMap */
$labelsMap = method_exists($enumClass, 'toLabels') ? $enumClass::toLabels() : [];
/** @var array<string, string|int> $valuesMap */
$valuesMap = method_exists($enumClass, 'toValues') ? $enumClass::toValues() : [];
foreach ($labelsMap as $enumName => $translatedLabel) {
$normalizedCsvLabel = $label->lower()->value();
$normalizedEnumLabel = Str::lower($translatedLabel);
if ($normalizedEnumLabel === $normalizedCsvLabel) {
return $enumClass::from(Arr::string($valuesMap, $enumName));
}
$sluggedCsv = $label->slug()->value();
$sluggedEnum = Str::of($translatedLabel)->slug()->value();
if (str_contains($sluggedEnum, $sluggedCsv) || str_contains($sluggedCsv, $sluggedEnum)) {
return $enumClass::from(Arr::string($valuesMap, $enumName));
}
}
return null;
}
private function applyLabelMappings(Stringable $label): Stringable
{
if ($label->endsWith('petits conditionnements')) {
$label = $label->replaceEnd('petits conditionnements', 'petit conditionnement');
}
$label = $label->replace('/', ' / ');
return $label;
}
}