<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20250109222633 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE user_join_level (user_id INT NOT NULL, level_id INT NOT NULL, INDEX IDX_B4CF7952A76ED395 (user_id), INDEX IDX_B4CF79525FB14BA7 (level_id), PRIMARY KEY(user_id, level_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE user_join_level ADD CONSTRAINT FK_B4CF7952A76ED395 FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE user_join_level ADD CONSTRAINT FK_B4CF79525FB14BA7 FOREIGN KEY (level_id) REFERENCES config_level (id) ON DELETE CASCADE');
$users = $this->connection->fetchAllAssociative('SELECT id, levels FROM user WHERE levels IS NOT NULL');
foreach ($users as $user) {
$userId = $user['id'];
$levelsArray = unserialize($user['levels']);
if (!\is_array($levelsArray)) {
continue;
}
foreach ($levelsArray as $levelName) {
switch ($levelName) {
case 'red': $levelName = 'ruby'; break;
case 'copper': $levelName = 'sapphire'; break;
case 'bronze': $levelName = 'emerald'; break;
}
$levelId = $this->connection->fetchOne('SELECT id FROM config_level WHERE name = ?', [$levelName]);
if ($levelId) {
$this->addSql('INSERT INTO user_join_level (user_id, level_id) VALUES (?, ?)', [$userId, $levelId]);
}
}
}
$this->addSql('ALTER TABLE user DROP levels');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE user ADD levels LONGTEXT DEFAULT NULL COLLATE `utf8mb4_general_ci` COMMENT \'(DC2Type:array)\'');
$userLevels = $this->connection->fetchAllAssociative('SELECT user_id, level_id FROM user_join_level');
$reverseMapping = [
'ruby' => 'red',
'sapphire' => 'copper',
'emerald' => 'bronze',
];
$userLevelsMap = [];
foreach ($userLevels as $userLevel) {
$userId = $userLevel['user_id'];
$levelName = $this->connection->fetchOne('SELECT name FROM config_level WHERE id = ?', [$userLevel['level_id']]);
if ($levelName) {
$levelName = strtolower($levelName);
$levelName = $reverseMapping[$levelName] ?? $levelName;
if (!isset($userLevelsMap[$userId])) {
$userLevelsMap[$userId] = [];
}
$userLevelsMap[$userId][] = $levelName;
}
}
foreach ($userLevelsMap as $userId => $levels) {
$serializedLevels = serialize($levels);
$this->addSql('UPDATE user SET levels = ? WHERE id = ?', [$serializedLevels, $userId]);
}
$this->addSql('DROP TABLE user_join_level');
}
}