Files
roi-theme/admin/includes/class-db-manager.php
FrankZamora 42edfab50d Fase-00: Configuración inicial del proyecto
- Configuración de Composer con PSR-4 en _testing-suite/
- Configuración de PHPUnit en _testing-suite/phpunit.xml
- Configuración de PHPCS en _testing-suite/phpcs.xml
- WordPress Test Suite integrado en bootstrap-integration.php
- Scripts de backup automatizado (backup-database.php, backup-files.bat)
- Procedimientos de rollback documentados (RESTORE-PROCEDURE.md)
- Estrategia de Git branching documentada (GIT-BRANCHING-STRATEGY.md)
- .gitignore actualizado para excluir _testing-suite/ y _planeacion/
- Limpieza de estructura anterior de Clean Architecture
- Documentación completa en _planeacion/roi-theme/_MIGRACION-CLEAN-ARCHITECTURE/Fase-00/

Archivos de configuración movidos a _testing-suite/:
- composer.json (PSR-4 autoloading, dev dependencies)
- phpunit.xml (3 suites: Unit, Integration, E2E)
- phpcs.xml (WordPress Coding Standards)
- bootstrap-unit.php y bootstrap-integration.php

Sistema de backup implementado con 4 mejoras críticas:
- Password protegido con --defaults-file
- Verificación de espacio en disco
- Lock files para prevenir ejecuciones concurrentes
- Detección automática de rutas

Procedimientos de rollback documentados:
- Rollback de base de datos (5-10 min)
- Rollback de archivos (10-15 min)
- Rollback de Git (5 min)
- Rollback completo (20-30 min)

Preparación del entorno completa. Listo para comenzar Fase-1.
2025-11-18 23:26:28 -06:00

319 lines
8.7 KiB
PHP

<?php
/**
* Database Manager Class
*
* Gestión de tablas personalizadas del tema
*
* @package ROI_Theme
* @since 2.2.0
* @deprecated 2.0.0 Use ROITheme\Infrastructure\Persistence\WordPress\WordPressComponentRepository instead
* @see ROITheme\Infrastructure\Persistence\WordPress\WordPressComponentRepository
*
* Esta clase será eliminada en la versión 3.0.0
* Por favor migre su código a la nueva arquitectura Clean Architecture
*/
if (!defined('ABSPATH')) {
exit;
}
/**
* ROI_DB_Manager
*
* @deprecated 2.0.0
*/
class ROI_DB_Manager {
/**
* Nombre de la tabla de componentes (sin prefijo)
*
* @deprecated 2.0.0
*/
const TABLE_COMPONENTS = 'roi_theme_components';
/**
* Nombre de la tabla de defaults (sin prefijo)
*
* @deprecated 2.0.0
*/
const TABLE_DEFAULTS = 'roi_theme_components_defaults';
/**
* Versión de la base de datos
*
* @deprecated 2.0.0
*/
const DB_VERSION = '1.0';
/**
* Opción para almacenar la versión de la DB
*
* @deprecated 2.0.0
*/
const DB_VERSION_OPTION = 'roi_db_version';
/**
* @var \ROITheme\Infrastructure\Adapters\LegacyDBManagerAdapter
*/
private $adapter;
/**
* Constructor
*
* @deprecated 2.0.0
*/
public function __construct() {
_deprecated_function(
__CLASS__ . '::__construct',
'2.0.0',
'ROITheme\Infrastructure\Persistence\WordPress\WordPressComponentRepository'
);
$this->logDeprecation(__CLASS__, __FUNCTION__);
// Hook para verificar/actualizar DB en cada carga
add_action('admin_init', array($this, 'maybe_create_tables'));
// Inicializar adapter para mantener compatibilidad
$this->adapter = $this->getLegacyAdapter();
}
/**
* Obtener nombre completo de tabla con prefijo
*
* @deprecated 2.0.0
*
* @param string $table_type Tipo de tabla: 'components' (personalizaciones) o 'defaults' (valores por defecto)
* @return string Nombre completo de la tabla con prefijo
*/
public function get_table_name($table_type = 'components') {
_deprecated_function(
__FUNCTION__,
'2.0.0',
'Direct database access not recommended - use repositories'
);
global $wpdb;
if ($table_type === 'defaults') {
return $wpdb->prefix . self::TABLE_DEFAULTS;
}
return $wpdb->prefix . self::TABLE_COMPONENTS;
}
/**
* Verificar si las tablas necesitan ser creadas o actualizadas
*
* @deprecated 2.0.0 Tables are now managed through database migrations
*/
public function maybe_create_tables() {
// Keep for backward compatibility but tables are managed differently now
$installed_version = get_option(self::DB_VERSION_OPTION);
if ($installed_version !== self::DB_VERSION) {
$this->create_tables();
update_option(self::DB_VERSION_OPTION, self::DB_VERSION);
}
}
/**
* Crear tablas personalizadas
*
* @deprecated 2.0.0 Use DatabaseMigrator service instead
*/
public function create_tables() {
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Infrastructure\Services\DatabaseMigrator'
);
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// Table structure (kept for backward compatibility)
$table_structure = "(
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
component_name VARCHAR(50) NOT NULL,
config_key VARCHAR(100) NOT NULL,
config_value TEXT NOT NULL,
data_type ENUM('string', 'boolean', 'integer', 'json') DEFAULT 'string',
version VARCHAR(10) DEFAULT NULL,
updated_at DATETIME NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY component_config (component_name, config_key),
INDEX idx_component (component_name),
INDEX idx_updated (updated_at)
) $charset_collate;";
// Create components table
$table_components = $this->get_table_name('components');
$sql_components = "CREATE TABLE IF NOT EXISTS $table_components $table_structure";
dbDelta($sql_components);
// Create defaults table
$table_defaults = $this->get_table_name('defaults');
$sql_defaults = "CREATE TABLE IF NOT EXISTS $table_defaults $table_structure";
dbDelta($sql_defaults);
}
/**
* Verificar si una tabla existe
*
* @deprecated 2.0.0
*
* @param string $table_type Tipo de tabla
* @return bool True si existe, false si no
*/
public function table_exists($table_type = 'components') {
global $wpdb;
$table_name = $this->get_table_name($table_type);
$query = $wpdb->prepare('SHOW TABLES LIKE %s', $table_name);
return $wpdb->get_var($query) === $table_name;
}
/**
* Save component configuration
*
* @deprecated 2.0.0 Use SaveComponentUseCase::execute() instead
*
* @param string $component_name Component name (e.g., 'top_notification_bar', 'navbar', 'footer', 'hero_section')
* @param string $config_key Configuration key
* @param mixed $config_value Configuration value
* @param string $data_type Data type (string, boolean, integer, array)
* @param string|null $version Schema version
* @param string $table_type Table type (components or defaults)
* @return bool Success status
*/
public function save_config($component_name, $config_key, $config_value, $data_type = 'string', $version = null, $table_type = 'components') {
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Application\UseCases\SaveComponent\SaveComponentUseCase::execute()'
);
$this->logDeprecation(__CLASS__, __FUNCTION__, func_get_args());
// Delegar al adapter para mantener funcionalidad
return $this->adapter->save_config(
$component_name,
$config_key,
$config_value,
$data_type,
$version,
$table_type
);
}
/**
* Get component configuration
*
* @deprecated 2.0.0 Use GetComponentUseCase::execute() instead
*
* @param string $component_name Component name
* @param string|null $config_key Specific configuration key (null for all)
* @param string $table_type Table type (components or defaults)
* @return mixed Configuration value(s) or null
*/
public function get_config($component_name, $config_key = null, $table_type = 'components') {
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Application\UseCases\GetComponent\GetComponentUseCase::execute()'
);
$this->logDeprecation(__CLASS__, __FUNCTION__, func_get_args());
return $this->adapter->get_config($component_name, $config_key, $table_type);
}
/**
* Delete component configuration
*
* @deprecated 2.0.0 Use DeleteComponentUseCase::execute() instead
*
* @param string $component_name Component name
* @param string|null $config_key Specific configuration key (null for all component)
* @param string $table_type Table type (components or defaults)
* @return bool Success status
*/
public function delete_config($component_name, $config_key = null, $table_type = 'components') {
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Application\UseCases\DeleteComponent\DeleteComponentUseCase::execute()'
);
$this->logDeprecation(__CLASS__, __FUNCTION__, func_get_args());
// If deleting specific key, not supported in new architecture
// Delete entire component instead
return $this->adapter->delete_config($component_name, $table_type);
}
/**
* List all components
*
* @deprecated 2.0.0 Use ComponentRepository::findAll() instead
*
* @param string $table_type Table type
* @return array List of components
*/
public function list_components($table_type = 'components') {
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Domain\Contracts\ComponentRepositoryInterface::findAll()'
);
$this->logDeprecation(__CLASS__, __FUNCTION__, func_get_args());
global $wpdb;
$table = $this->get_table_name($table_type);
$query = "SELECT DISTINCT component_name FROM $table ORDER BY component_name ASC";
$components = $wpdb->get_col($query);
return $components ?: array();
}
/**
* Get legacy adapter
*
* @return \ROITheme\Infrastructure\Adapters\LegacyDBManagerAdapter
*/
private function getLegacyAdapter() {
if (!class_exists('ROITheme\Infrastructure\Adapters\LegacyDBManagerAdapter')) {
require_once get_template_directory() . '/vendor/autoload.php';
}
return new \ROITheme\Infrastructure\Adapters\LegacyDBManagerAdapter();
}
/**
* Log deprecation usage
*
* @param string $class Class name
* @param string $method Method name
* @param array $args Arguments
*/
private function logDeprecation($class, $method, $args = array()) {
if (!class_exists('ROITheme\Infrastructure\Logging\DeprecationLogger')) {
require_once get_template_directory() . '/vendor/autoload.php';
}
$logger = \ROITheme\Infrastructure\Logging\DeprecationLogger::getInstance();
$logger->log(
$class,
$method,
$args,
'See documentation for Clean Architecture migration',
'2.0.0'
);
}
}