<?php
declare(strict_types=1);
namespace RecurringInvoicesBundleMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
use Symfony\Component\Uid\UuidV6;
final class Version20240710092649 extends AbstractMigration
{
private array $lines;
public function preUp(Schema $schema): void
{
parent::preUp($schema);
$this->lines = $this->connection->executeQuery(
'SELECT * FROM recurring_invoices_bundle__recurring_invoice_line'
)->fetchAllAssociative();
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE recurring_invoices_bundle__recurring_invoice_line ADD product_id BINARY(16) DEFAULT NULL COMMENT \'(DC2Type:uuid)\', ADD declination_id BINARY(16) DEFAULT NULL COMMENT \'(DC2Type:uuid)\'');
$this->addSql('ALTER TABLE recurring_invoices_bundle__recurring_invoice_line ADD CONSTRAINT FK_BD96F0684584665A FOREIGN KEY (product_id) REFERENCES products_bundle__product (id)');
$this->addSql('ALTER TABLE recurring_invoices_bundle__recurring_invoice_line ADD CONSTRAINT FK_BD96F0689941A932 FOREIGN KEY (declination_id) REFERENCES products_bundle__declination (id)');
$this->addSql('CREATE INDEX IDX_BD96F0684584665A ON recurring_invoices_bundle__recurring_invoice_line (product_id)');
$this->addSql('CREATE INDEX IDX_BD96F0689941A932 ON recurring_invoices_bundle__recurring_invoice_line (declination_id)');
}
public function postUp(Schema $schema): void
{
parent::postUp($schema);
foreach ($this->lines as $line) {
$lineId = UuidV6::fromBinary($line['id'])->toRfc4122();
$options = json_decode($line['options'], true);
if (!empty($options['product'])) {
$productOptions = $options['product'];
$decliId = !empty($productOptions['declination_id']) ?
'0x' . str_replace('-', '', $productOptions['declination_id']) : null
;
$productId = '0x' . str_replace('-', '', $productOptions['id']);
$query = "UPDATE recurring_invoices_bundle__recurring_invoice_line SET product_id = " . $productId;
if ($decliId) {
$query .= ", declination_id = " . $decliId;
}
$query .= " WHERE id = UNHEX(CONCAT('', REPLACE('" . $lineId . "', '-', '')))";
$this->connection->executeStatement($query);
}
}
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE recurring_invoices_bundle__recurring_invoice_line DROP FOREIGN KEY FK_BD96F0684584665A');
$this->addSql('ALTER TABLE recurring_invoices_bundle__recurring_invoice_line DROP FOREIGN KEY FK_BD96F0689941A932');
$this->addSql('DROP INDEX IDX_BD96F0684584665A ON recurring_invoices_bundle__recurring_invoice_line');
$this->addSql('DROP INDEX IDX_BD96F0689941A932 ON recurring_invoices_bundle__recurring_invoice_line');
$this->addSql('ALTER TABLE recurring_invoices_bundle__recurring_invoice_line DROP product_id, DROP declination_id');
}
}