app/DoctrineMigrations/Version20241213100000.php line 1

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace DoctrineMigrations;
  4. use Doctrine\DBAL\Schema\Schema;
  5. use Doctrine\Migrations\AbstractMigration;
  6. final class Version202412131100000 extends AbstractMigration
  7. {
  8.     public function getDescription(): string
  9.     {
  10.         return 'Truncate maker table and import initial data from CSV';
  11.     }
  12.     private function loadCsvData(): array
  13.     {
  14.         $csvPath __DIR__ '/Data/makers.csv';
  15.         
  16.         if (!file_exists($csvPath)) {
  17.             throw new \RuntimeException('CSV file not found: ' $csvPath);
  18.         }
  19.         $data = [];
  20.         if (($handle fopen($csvPath'r')) !== false) {
  21.             // ヘッダー行をスキップ
  22.             fgetcsv($handle);
  23.             
  24.             while (($row fgetcsv($handle)) !== false) {
  25.                 $data[] = [
  26.                     'id' => $row[0],
  27.                     'name_en' => $row[1],
  28.                     'name_jp' => $row[2],
  29.                 ];
  30.             }
  31.             fclose($handle);
  32.         }
  33.         
  34.         return $data;
  35.     }
  36.     public function up(Schema $schema): void
  37.     {
  38.         // 外部キー制約を一時的に無効化(必要な場合)
  39.         $this->addSql('SET FOREIGN_KEY_CHECKS = 0');
  40.         
  41.         // テーブルをクリア
  42.         $this->addSql('TRUNCATE TABLE dtb_maker');
  43.         
  44.         try {
  45.             $makers $this->loadCsvData();
  46.             
  47.             foreach ($makers as $maker) {
  48.                 $this->addSql(
  49.                     'INSERT INTO dtb_maker (id, name_en, name_jp, create_date, update_date, discriminator_type) 
  50.                     VALUES (?, ?, ?, NOW(), NOW(), \'maker\')',
  51.                     [$maker['id'], $maker['name_en'], $maker['name_jp']]
  52.                 );
  53.             }
  54.         } catch (\Exception $e) {
  55.             $this->write('Migration failed: ' $e->getMessage());
  56.             throw $e;
  57.         } finally {
  58.             // 外部キー制約を再有効化
  59.             $this->addSql('SET FOREIGN_KEY_CHECKS = 1');
  60.         }
  61.     }
  62.     public function down(Schema $schema): void
  63.     {
  64.         // ロールバック時の処理
  65.         $this->addSql('TRUNCATE TABLE dtb_maker');
  66.     }
  67. }