ogcore/migrations/Version20260417132000.php

60 lines
2.8 KiB
PHP

<?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 Version20260417132000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create DhcpServer entity and link to Subnet';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE dhcp_server (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, ip VARCHAR(255) NOT NULL, api_port INT DEFAULT 8006 NOT NULL, comments VARCHAR(255) DEFAULT NULL, uuid CHAR(36) NOT NULL COMMENT \'(DC2Type:uuid)\', UNIQUE INDEX UNIQ_IDENTIFIER_IP (ip), UNIQUE INDEX UNIQ_IDENTIFIER_NAME (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE subnet ADD dhcp_server_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE subnet ADD CONSTRAINT FK_50551F51C2C88941 FOREIGN KEY (dhcp_server_id) REFERENCES dhcp_server (id)');
$this->addSql('CREATE INDEX IDX_50551F51C2C88941 ON subnet (dhcp_server_id)');
// Extract old legacy DHCP URL from env.json if exists, else fallback
$url = '127.0.0.1:8081';
$envFile = __DIR__ . '/../env.json';
if (file_exists($envFile)) {
$envData = json_decode(file_get_contents($envFile), true);
if (isset($envData['vars']['OG_DHCP_API_URL'])) {
$url = $envData['vars']['OG_DHCP_API_URL'];
}
}
// Normalize URL format before parsing since env.json stores it raw like '127.0.0.1:8081'
$url = (str_starts_with($url, 'http')) ? $url : 'http://' . $url;
$parsed = parse_url($url);
$ip = $parsed['host'] ?? '127.0.0.1';
$port = isset($parsed['port']) ? $parsed['port'] : 8081;
// Create a default instance to absorb existing subnets and prevent orphans
$this->addSql(sprintf("INSERT INTO dhcp_server (name, ip, api_port, uuid) VALUES ('Servidor DHCP Local (Migrado)', '%s', %d, UUID())", $ip, $port));
// Relink all existing orphan subnets to this newly created default server
$this->addSql("UPDATE subnet SET dhcp_server_id = (SELECT id FROM dhcp_server LIMIT 1) WHERE dhcp_server_id IS NULL");
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE subnet DROP FOREIGN KEY FK_50551F51C2C88941');
$this->addSql('DROP TABLE dhcp_server');
$this->addSql('DROP INDEX IDX_50551F51C2C88941 ON subnet');
$this->addSql('ALTER TABLE subnet DROP dhcp_server_id');
}
}