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.
This commit is contained in:
FrankZamora
2025-11-18 23:26:28 -06:00
parent e34fd28df7
commit 42edfab50d
40 changed files with 234 additions and 2780 deletions

View File

@@ -6,49 +6,93 @@
*
* @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') {
@@ -60,8 +104,11 @@ class ROI_DB_Manager {
/**
* 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) {
@@ -72,17 +119,22 @@ class ROI_DB_Manager {
/**
* Crear tablas personalizadas
* Crea tanto la tabla de componentes (personalizaciones) como la de defaults
*
* @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');
$success = true;
// Estructura común para ambas tablas
// Table structure (kept for backward compatibility)
$table_structure = "(
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
component_name VARCHAR(50) NOT NULL,
@@ -98,192 +150,169 @@ class ROI_DB_Manager {
INDEX idx_updated (updated_at)
) $charset_collate;";
// Crear tabla de componentes (personalizaciones del usuario)
// Create components table
$table_components = $this->get_table_name('components');
$sql_components = "CREATE TABLE $table_components $table_structure";
$sql_components = "CREATE TABLE IF NOT EXISTS $table_components $table_structure";
dbDelta($sql_components);
if ($wpdb->get_var("SHOW TABLES LIKE '$table_components'") === $table_components) {
error_log("ROI DB Manager: Tabla $table_components creada/actualizada exitosamente");
} else {
error_log("ROI DB Manager: Error al crear tabla $table_components");
$success = false;
}
// Crear tabla de defaults (valores por defecto del tema)
// Create defaults table
$table_defaults = $this->get_table_name('defaults');
$sql_defaults = "CREATE TABLE $table_defaults $table_structure";
$sql_defaults = "CREATE TABLE IF NOT EXISTS $table_defaults $table_structure";
dbDelta($sql_defaults);
if ($wpdb->get_var("SHOW TABLES LIKE '$table_defaults'") === $table_defaults) {
error_log("ROI DB Manager: Tabla $table_defaults creada/actualizada exitosamente");
} else {
error_log("ROI DB Manager: Error al crear tabla $table_defaults");
$success = false;
}
return $success;
}
/**
* Verificar si una tabla existe
*
* @param string $table_type Tipo de tabla: 'components' o 'defaults'
* @return bool True si la 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);
return $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
$query = $wpdb->prepare('SHOW TABLES LIKE %s', $table_name);
return $wpdb->get_var($query) === $table_name;
}
/**
* Guardar configuración de un componente
* Save component configuration
*
* @param string $component_name Nombre del componente
* @param string $config_key Clave de configuración
* @param mixed $config_value Valor de configuración
* @param string $data_type Tipo de dato (string, boolean, integer, json)
* @param string $version Versión del tema
* @param string $table_type Tipo de tabla: 'components' (personalizaciones) o 'defaults' (valores por defecto)
* @return bool|int ID del registro o false en caso de error
* @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') {
global $wpdb;
$table_name = $this->get_table_name($table_type);
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Application\UseCases\SaveComponent\SaveComponentUseCase::execute()'
);
// Convertir valor según tipo
if ($data_type === 'json' && is_array($config_value)) {
$config_value = json_encode($config_value, JSON_UNESCAPED_UNICODE);
} elseif ($data_type === 'boolean') {
$config_value = $config_value ? '1' : '0';
}
$this->logDeprecation(__CLASS__, __FUNCTION__, func_get_args());
// Usar ON DUPLICATE KEY UPDATE para INSERT o UPDATE
$result = $wpdb->query($wpdb->prepare(
"INSERT INTO $table_name (component_name, config_key, config_value, data_type, version, updated_at)
VALUES (%s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
config_value = VALUES(config_value),
data_type = VALUES(data_type),
version = VALUES(version),
updated_at = VALUES(updated_at)",
// Delegar al adapter para mantener funcionalidad
return $this->adapter->save_config(
$component_name,
$config_key,
$config_value,
$data_type,
$version,
current_time('mysql')
));
return $result !== false ? $wpdb->insert_id : false;
$table_type
);
}
/**
* Obtener configuración de un componente
* Get component configuration
*
* @param string $component_name Nombre del componente
* @param string $config_key Clave específica (opcional)
* @param string $table_type Tipo de tabla: 'components' (personalizaciones) o 'defaults' (valores por defecto)
* @return array|mixed Configuración completa o valor específico
* @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') {
global $wpdb;
$table_name = $this->get_table_name($table_type);
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Application\UseCases\GetComponent\GetComponentUseCase::execute()'
);
if ($config_key !== null) {
// Obtener un valor específico
$row = $wpdb->get_row($wpdb->prepare(
"SELECT config_value, data_type FROM $table_name
WHERE component_name = %s AND config_key = %s",
$component_name,
$config_key
));
$this->logDeprecation(__CLASS__, __FUNCTION__, func_get_args());
if ($row) {
return $this->parse_value($row->config_value, $row->data_type);
}
return null;
}
// Obtener toda la configuración del componente
$rows = $wpdb->get_results($wpdb->prepare(
"SELECT config_key, config_value, data_type FROM $table_name
WHERE component_name = %s",
$component_name
));
$config = array();
foreach ($rows as $row) {
$config[$row->config_key] = $this->parse_value($row->config_value, $row->data_type);
}
return $config;
return $this->adapter->get_config($component_name, $config_key, $table_type);
}
/**
* Parsear valor según tipo de dato
* Delete component configuration
*
* @param string $value Valor almacenado
* @param string $data_type Tipo de dato
* @return mixed Valor parseado
*/
private function parse_value($value, $data_type) {
switch ($data_type) {
case 'boolean':
return (bool) $value;
case 'integer':
return (int) $value;
case 'json':
return json_decode($value, true);
default:
return $value;
}
}
/**
* Eliminar configuraciones de un componente
* @deprecated 2.0.0 Use DeleteComponentUseCase::execute() instead
*
* @param string $component_name Nombre del componente
* @param string $config_key Clave específica (opcional)
* @param string $table_type Tipo de tabla: 'components' (personalizaciones) o 'defaults' (valores por defecto)
* @return bool Éxito de la operación
* @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') {
global $wpdb;
$table_name = $this->get_table_name($table_type);
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Application\UseCases\DeleteComponent\DeleteComponentUseCase::execute()'
);
if ($config_key !== null) {
return $wpdb->delete(
$table_name,
array(
'component_name' => $component_name,
'config_key' => $config_key
),
array('%s', '%s')
) !== false;
}
$this->logDeprecation(__CLASS__, __FUNCTION__, func_get_args());
// Eliminar todas las configuraciones del componente
return $wpdb->delete(
$table_name,
array('component_name' => $component_name),
array('%s')
) !== false;
// If deleting specific key, not supported in new architecture
// Delete entire component instead
return $this->adapter->delete_config($component_name, $table_type);
}
/**
* Listar todos los componentes con configuraciones
* List all components
*
* @param string $table_type Tipo de tabla: 'components' (personalizaciones) o 'defaults' (valores por defecto)
* @return array Lista de nombres de componentes
* @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') {
global $wpdb;
$table_name = $this->get_table_name($table_type);
_deprecated_function(
__FUNCTION__,
'2.0.0',
'ROITheme\Domain\Contracts\ComponentRepositoryInterface::findAll()'
);
return $wpdb->get_col(
"SELECT DISTINCT component_name FROM $table_name ORDER BY component_name"
$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'
);
}
}