<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version202412131100000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Truncate maker table and import initial data from CSV';
}
private function loadCsvData(): array
{
$csvPath = __DIR__ . '/Data/makers.csv';
if (!file_exists($csvPath)) {
throw new \RuntimeException('CSV file not found: ' . $csvPath);
}
$data = [];
if (($handle = fopen($csvPath, 'r')) !== false) {
// ヘッダー行をスキップ
fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
$data[] = [
'id' => $row[0],
'name_en' => $row[1],
'name_jp' => $row[2],
];
}
fclose($handle);
}
return $data;
}
public function up(Schema $schema): void
{
// 外部キー制約を一時的に無効化(必要な場合)
$this->addSql('SET FOREIGN_KEY_CHECKS = 0');
// テーブルをクリア
$this->addSql('TRUNCATE TABLE dtb_maker');
try {
$makers = $this->loadCsvData();
foreach ($makers as $maker) {
$this->addSql(
'INSERT INTO dtb_maker (id, name_en, name_jp, create_date, update_date, discriminator_type)
VALUES (?, ?, ?, NOW(), NOW(), \'maker\')',
[$maker['id'], $maker['name_en'], $maker['name_jp']]
);
}
} catch (\Exception $e) {
$this->write('Migration failed: ' . $e->getMessage());
throw $e;
} finally {
// 外部キー制約を再有効化
$this->addSql('SET FOREIGN_KEY_CHECKS = 1');
}
}
public function down(Schema $schema): void
{
// ロールバック時の処理
$this->addSql('TRUNCATE TABLE dtb_maker');
}
}