Files
MoneyFlix/crm/Core/Database/MigrationManager.php
T
1sonhador 8542395fbe Add public campaign analytics functionality
- Add PublicCampaignsController for public campaign analytics
- Add public routes for /public/analytics/{slug} and /api/campaigns/{slug}
- Add public campaign analytics view with charts and KPIs
- Support for campaign sharing via custom slugs
- Real-time analytics with ApexCharts integration
2025-10-15 00:30:00 +01:00

474 lines
16 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace App\Core\Database;
use App\Core\DatabaseManager;
use App\Core\ErrorReporter;
use App\Core\Logger;
use App\Core\PathManager;
class MigrationManager
{
private DatabaseManager $db;
private SchemaBuilder $schema;
private Logger $logger;
private string $migrationsPath;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
$this->schema = new SchemaBuilder();
$this->logger = new Logger();
// No longer needed - all migrations are now in modules
$this->migrationsPath = '';
}
/**
* Run all pending migrations with intelligent system
*/
public function migrate(): array
{
$results = [
'applied' => [],
'skipped' => [],
'errors' => [],
'warnings' => []
];
try {
$this->logger->info("🚀 Starting intelligent migration system");
// Ensure migrations table exists
$this->ensureMigrationsTable();
// Get all migration files from both old and new locations
$migrationFiles = $this->getAllMigrationFiles();
$processedMigrations = [];
$this->logger->info("📋 Found " . count($migrationFiles) . " migration files");
foreach ($migrationFiles as $file) {
$migration = $this->loadMigration($file);
if (!$migration) {
$error = "Failed to load migration: $file";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
continue;
}
$migrationName = $migration->getName();
// Skip if we already processed this migration
if (in_array($migrationName, $processedMigrations)) {
$this->logger->info("⏭️ Skipping duplicate migration: $migrationName");
continue;
}
$processedMigrations[] = $migrationName;
if ($migration->isApplied()) {
$results['skipped'][] = $migrationName;
$this->logger->info("✅ Migration already applied: $migrationName");
continue;
}
$this->logger->info("🔄 Running migration: $migrationName");
// Run the migration with intelligent system
if ($migration->run()) {
$migration->markAsApplied();
$results['applied'][] = $migrationName;
$this->logger->info("✅ Migration applied successfully: $migrationName");
} else {
$error = "Migration failed: $migrationName";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
}
}
$this->logger->info("🎉 Migration system completed");
$this->logger->info("📊 Results: " . count($results['applied']) . " applied, " .
count($results['skipped']) . " skipped, " .
count($results['errors']) . " errors");
} catch (\Exception $e) {
$error = "Migration system error: " . $e->getMessage();
$results['errors'][] = $error;
$this->logger->error("❌ $error");
ErrorReporter::report($e, ['context' => 'migration_manager_migrate']);
}
return $results;
}
/**
* Rollback last batch of migrations with safety checks
*/
public function rollback(int $steps = 1): array
{
$results = [
'rolled_back' => [],
'errors' => [],
'warnings' => []
];
try {
$this->logger->info("🔄 Starting rollback of $steps migration(s)");
$migrations = $this->getLastBatchMigrations($steps);
if (empty($migrations)) {
$this->logger->info("ℹ️ No migrations to rollback");
return $results;
}
foreach ($migrations as $migrationName) {
$migration = $this->loadMigrationByName($migrationName);
if (!$migration) {
$error = "Failed to load migration for rollback: $migrationName";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
continue;
}
$this->logger->info("🔄 Rolling back migration: $migrationName");
if ($migration->rollback()) {
$migration->markAsRolledBack();
$results['rolled_back'][] = $migrationName;
$this->logger->info("✅ Migration rolled back successfully: $migrationName");
} else {
$error = "Rollback failed: $migrationName";
$results['errors'][] = $error;
$this->logger->error("❌ $error");
}
}
$this->logger->info("🎉 Rollback completed");
$this->logger->info("📊 Results: " . count($results['rolled_back']) . " rolled back, " .
count($results['errors']) . " errors");
} catch (\Exception $e) {
$error = "Rollback system error: " . $e->getMessage();
$results['errors'][] = $error;
$this->logger->error("❌ $error");
ErrorReporter::report($e, ['context' => 'migration_manager_rollback']);
}
return $results;
}
/**
* Show migration status with detailed information
*/
public function status(): array
{
$status = [];
try {
$this->logger->info("📊 Checking migration status");
$migrationFiles = $this->getAllMigrationFiles();
$appliedMigrations = $this->getAppliedMigrations();
$processedMigrations = [];
$this->logger->info("📋 Found " . count($migrationFiles) . " migration files");
$this->logger->info("✅ Found " . count($appliedMigrations) . " applied migrations");
foreach ($migrationFiles as $file) {
$migration = $this->loadMigration($file);
if (!$migration) continue;
$migrationName = $migration->getName();
// Skip if we already processed this migration
if (in_array($migrationName, $processedMigrations)) {
continue;
}
$processedMigrations[] = $migrationName;
$isApplied = in_array($migrationName, $appliedMigrations);
$status[] = [
'name' => $migrationName,
'file' => basename($file),
'applied' => $isApplied,
'applied_at' => $isApplied ? $this->getMigrationAppliedAt($migrationName) : null,
'status' => $isApplied ? '✅ Applied' : '⏳ Pending'
];
}
$this->logger->info("📊 Status check completed");
} catch (\Exception $e) {
$this->logger->error("❌ Status check error: " . $e->getMessage());
ErrorReporter::report($e, ['context' => 'migration_manager_status']);
}
return $status;
}
/**
* Get all migration files from module directories
*/
private function getAllMigrationFiles(): array
{
return PathManager::getAllMigrationFiles();
}
/**
* Load migration from file with error handling
*/
private function loadMigration(string $file): ?Migration
{
try {
// Get the file content to extract the class name
$content = file_get_contents($file);
// Extract class name using regex
if (preg_match('/class\s+(\w+)\s+extends\s+Migration/', $content, $matches)) {
$className = $matches[1];
// Get the namespace from the file
$namespace = '';
if (preg_match('/namespace\s+([^;]+);/', $content, $namespaceMatches)) {
$namespace = $namespaceMatches[1] . '\\';
}
$fullClassName = $namespace . $className;
// Load the file
require_once $file;
// Check if the class exists and is a subclass of Migration
if (class_exists($fullClassName) && is_subclass_of($fullClassName, 'App\Core\Database\Migration')) {
return new $fullClassName();
}
}
$this->logger->warning("⚠️ Could not load migration from file: $file");
return null;
} catch (\Exception $e) {
$this->logger->error("❌ Error loading migration from file $file: " . $e->getMessage());
ErrorReporter::report($e, ['context' => 'migration_manager_load', 'file' => $file]);
return null;
}
}
/**
* Load migration by class name
*/
private function loadMigrationByName(string $migrationName): ?Migration
{
$files = $this->getAllMigrationFiles();
foreach ($files as $file) {
$migration = $this->loadMigration($file);
if ($migration && $migration->getName() === $migrationName) {
return $migration;
}
}
$this->logger->warning("⚠️ Could not find migration: $migrationName");
return null;
}
/**
* Get applied migrations
*/
private function getAppliedMigrations(): array
{
try {
$result = $this->db->fetchAll("SELECT migration FROM migrations ORDER BY executed_at ASC");
return array_column($result, 'migration');
} catch (\Exception $e) {
$this->logger->warning("⚠️ Could not get applied migrations: " . $e->getMessage());
return [];
}
}
/**
* Get last batch migrations
*/
private function getLastBatchMigrations(int $steps = 1): array
{
try {
// Sanitize steps to prevent SQL injection
$steps = max(1, min(100, (int)$steps));
$result = $this->db->fetchAll(
"SELECT migration FROM migrations ORDER BY batch DESC, executed_at DESC LIMIT " . $steps
);
return array_column($result, 'migration');
} catch (\Exception $e) {
$this->logger->warning("⚠️ Could not get last batch migrations: " . $e->getMessage());
return [];
}
}
/**
* Get migration applied timestamp
*/
private function getMigrationAppliedAt(string $migrationName): ?string
{
try {
$result = $this->db->fetch(
"SELECT executed_at FROM migrations WHERE migration = ?",
[$migrationName]
);
return $result['executed_at'] ?? null;
} catch (\Exception $e) {
$this->logger->warning("⚠️ Could not get migration timestamp for $migrationName: " . $e->getMessage());
return null;
}
}
/**
* Ensure migrations table exists with intelligent system
*/
private function ensureMigrationsTable(): void
{
if (!$this->schema->tableExists('migrations')) {
$this->logger->info("📋 Creating migrations table");
$this->schema->table('migrations')
->bigInteger('id')->autoIncrement()->notNull()
->string('migration', 255)->notNull()
->integer('batch')->notNull()
->timestamp('executed_at')->notNull()
->primaryKey('id')
->index('migration')
->index('batch')
->apply();
$this->logger->info("✅ Migrations table created successfully");
} else {
$this->logger->info("✅ Migrations table already exists");
}
}
/**
* Get database schema diff using intelligent system
*/
public function getSchemaDiff(string $tableName, array $desiredColumns, array $desiredIndexes = []): array
{
$this->logger->info("🔍 Getting schema diff for table: $tableName");
return $this->schema->compareStructures($tableName, $desiredColumns, $desiredIndexes);
}
/**
* Apply schema changes using intelligent system
*/
public function applySchemaChanges(string $tableName, array $changes): bool
{
$this->logger->info("🚀 Applying schema changes to table: $tableName");
return $this->schema->applyChanges($tableName, $changes);
}
/**
* Get current table structure
*/
public function getTableStructure(string $tableName): array
{
return $this->schema->getCurrentStructure($tableName);
}
/**
* Get current table indexes
*/
public function getTableIndexes(string $tableName): array
{
return $this->schema->getCurrentIndexes($tableName);
}
/**
* Check if table exists
*/
public function tableExists(string $tableName): bool
{
return $this->schema->tableExists($tableName);
}
/**
* Get all tables
*/
public function getTables(): array
{
return $this->schema->getTables();
}
/**
* Validate database integrity
*/
public function validateDatabaseIntegrity(): array
{
$results = [
'valid' => true,
'issues' => [],
'warnings' => []
];
try {
$this->logger->info("🔍 Validating database integrity");
$tables = $this->getTables();
foreach ($tables as $tableName) {
// Check if table has primary key
$hasPrimaryKey = $this->db->fetch("
SELECT COUNT(*) as count
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND CONSTRAINT_NAME = 'PRIMARY'
", [$tableName]);
if (($hasPrimaryKey['count'] ?? 0) === 0) {
$warning = "Table $tableName has no PRIMARY KEY";
$results['warnings'][] = $warning;
$this->logger->warning("⚠️ $warning");
}
// Check for orphaned indexes
$indexes = $this->getTableIndexes($tableName);
foreach ($indexes as $indexName => $index) {
if ($indexName !== 'PRIMARY') {
// Check if all columns in index still exist
foreach ($index['columns'] as $column) {
$columnExists = $this->db->fetch("
SELECT COUNT(*) as count
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?
", [$tableName, $column['name']]);
if (($columnExists['count'] ?? 0) === 0) {
$issue = "Index $indexName in table $tableName references non-existent column {$column['name']}";
$results['issues'][] = $issue;
$this->logger->error("❌ $issue");
$results['valid'] = false;
}
}
}
}
}
$this->logger->info("✅ Database integrity validation completed");
$this->logger->info("📊 Results: " . count($results['issues']) . " issues, " .
count($results['warnings']) . " warnings");
} catch (\Exception $e) {
$error = "Database integrity validation error: " . $e->getMessage();
$results['issues'][] = $error;
$results['valid'] = false;
$this->logger->error("❌ $error");
ErrorReporter::report($e, ['context' => 'migration_manager_validate_integrity']);
}
return $results;
}
}