Version20240803144323.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. declare(strict_types=1);
  3. namespace DoctrineMigrations;
  4. use Doctrine\DBAL\Schema\Schema;
  5. use Doctrine\Migrations\AbstractMigration;
  6. /**
  7. * Auto-generated Migration: Please modify to your needs!
  8. */
  9. final class Version20240803144323 extends AbstractMigration
  10. {
  11. public function getDescription(): string
  12. {
  13. return '';
  14. }
  15. public function up(Schema $schema): void
  16. {
  17. $this->addSql('
  18. ALTER TABLE user MODIFY roles LONGTEXT
  19. ');
  20. // Fetch all users to update their roles
  21. $users = $this->connection->fetchAllAssociative('SELECT id, roles FROM user');
  22. foreach ($users as $user) {
  23. $roles = unserialize($user['roles']);
  24. $jsonRoles = json_encode($roles);
  25. $this->addSql('UPDATE user SET roles = ? WHERE id = ?', [$jsonRoles, $user['id']]);
  26. }
  27. $this->addSql('
  28. ALTER TABLE user MODIFY roles JSON
  29. ');
  30. // this up() migration is auto-generated, please modify it to your needs
  31. $this->addSql('ALTER TABLE user CHANGE roles roles JSON NOT NULL');
  32. // Convert the roles column data from longtext to JSON
  33. }
  34. public function down(Schema $schema): void
  35. {
  36. // this down() migration is auto-generated, please modify it to your needs
  37. // Reverse the conversion if necessary
  38. $users = $this->connection->fetchAllAssociative('SELECT id, roles FROM user');
  39. foreach ($users as $user) {
  40. $roles = json_decode($user['roles'], true);
  41. $serializedRoles = serialize($roles);
  42. $this->addSql('UPDATE user SET roles = ? WHERE id = ?', [$serializedRoles, $user['id']]);
  43. }
  44. $this->addSql('
  45. ALTER TABLE user MODIFY roles LONGTEXT
  46. ');
  47. $this->addSql('ALTER TABLE user CHANGE roles roles LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\'');
  48. }
  49. }