Subir proyecto

This commit is contained in:
Gabriel
2026-10-08 10:39:09 -06:00
commit 3a971d1d0b
8344 changed files with 2765102 additions and 0 deletions
@@ -0,0 +1,54 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use JooosiFon\Database\Migration\Exception\AbortMigration;
use JooosiFon\Database\Migration\Exception\SkipMigration;
/**
* Base class for Jooosi Fon schema migrations.
*/
abstract class AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function abortIf(bool $condition, string $message = 'Unknown reason'): void
{
if ($condition) {
throw new AbortMigration($message);
}
}
public function skipIf(bool $condition, string $message = 'Unknown reason'): void
{
if ($condition) {
throw new SkipMigration($message);
}
}
public function preUp(): void
{
}
public function postUp(): void
{
}
public function preDown(): void
{
}
public function postDown(): void
{
}
abstract public function up(): void;
public function down(): void
{
$this->abortIf(\true, sprintf('No down() migration implemented for "%s".', static::class));
}
protected function collation(): string
{
global $wpdb;
if (!$wpdb->has_cap('collation')) {
return '';
}
return $wpdb->get_charset_collate();
}
}
@@ -0,0 +1,8 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
final class AbortMigration extends \JooosiFon\Database\Migration\Exception\MigrationException
{
}
@@ -0,0 +1,9 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
use RuntimeException;
class MigrationException extends RuntimeException
{
}
@@ -0,0 +1,8 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration\Exception;
final class SkipMigration extends \JooosiFon\Database\Migration\Exception\MigrationException
{
}
@@ -0,0 +1,63 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use WP_CLI_Command;
use function WP_CLI\Utils\format_items;
/**
* WP-CLI commands for Jooosi Fon migrations.
*/
final class MigrationCommand extends WP_CLI_Command
{
private \JooosiFon\Database\Migration\MigrationManager $manager;
public function __construct(\JooosiFon\Database\Migration\MigrationManager $manager)
{
$this->manager = $manager;
}
/**
* Generate a migration stub.
*
* ## OPTIONS
*
* [--table-name=<table-name>]
* : Optionally prefill a create/drop table migration.
*
* @when wp_loaded
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function generate(array $args, array $assocArgs): void
{
$tableName = isset($assocArgs['table-name']) ? sanitize_key((string) $assocArgs['table-name']) : null;
$path = $this->manager->generate($tableName);
\WP_CLI::success(sprintf('Generated migration: %s', $path));
}
/**
* List discovered migrations and their execution state.
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function list(array $args, array $assocArgs): void
{
format_items('table', $this->manager->list(), ['version', 'executed_at', 'execution_time', 'executed']);
}
/**
* Run all pending migrations.
*
* @param array<int, string> $args
* @param array<string, mixed> $assocArgs
*/
public function run(array $args, array $assocArgs): void
{
$executed = $this->manager->execute();
if ($executed === []) {
\WP_CLI::success('No pending migrations.');
return;
}
format_items('table', $executed, ['version', 'executed_at', 'execution_time']);
\WP_CLI::success(sprintf('%d migration(s) executed.', count($executed)));
}
}
@@ -0,0 +1,52 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
/**
* Immutable configuration for the plugin's migration subsystem.
*/
final class MigrationConfiguration
{
private string $tableName;
private string $namespace;
private string $directory;
private string $basePath;
private string $commandNamespace;
/**
* @param array<string, string> $configuration
*/
public function __construct(array $configuration = [])
{
$configuration = array_merge(['tableName' => 'jooosi_fon_migrations', 'namespace' => 'JooosiFon\Migrations', 'directory' => 'migrations', 'basePath' => dirname(__DIR__, 3), 'commandNamespace' => 'jooosi-fon migrations'], $configuration);
$this->tableName = $configuration['tableName'];
$this->namespace = trim($configuration['namespace'], '\\');
$this->directory = trim($configuration['directory'], \DIRECTORY_SEPARATOR);
$this->basePath = rtrim($configuration['basePath'], \DIRECTORY_SEPARATOR);
$this->commandNamespace = $configuration['commandNamespace'];
}
public function tableName(): string
{
return $this->tableName;
}
public function namespace(): string
{
return $this->namespace;
}
public function directory(): string
{
return $this->directory;
}
public function basePath(): string
{
return $this->basePath;
}
public function migrationsPath(): string
{
return $this->basePath . \DIRECTORY_SEPARATOR . $this->directory;
}
public function commandNamespace(): string
{
return $this->commandNamespace;
}
}
@@ -0,0 +1,21 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
/**
* Metadata for a discovered migration.
*/
final class MigrationDefinition
{
public string $version;
public string $className;
public string $description;
public function __construct(string $className, string $description)
{
// Existing installations store the fully-qualified class name as the version.
$this->version = $className;
$this->className = $className;
$this->description = $description;
}
}
@@ -0,0 +1,91 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use DateTimeImmutable;
use DateTimeZone;
use RuntimeException;
/**
* Generates migration stubs for WP-CLI.
*/
final class MigrationGenerator
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
public function __construct(\JooosiFon\Database\Migration\MigrationConfiguration $configuration)
{
$this->configuration = $configuration;
}
public function generate(?string $tableName = null): string
{
$className = 'Version' . (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format('YmdHis');
$directory = $this->configuration->migrationsPath();
$path = $directory . \DIRECTORY_SEPARATOR . $className . '.php';
if (!is_dir($directory) && !wp_mkdir_p($directory)) {
throw new RuntimeException(sprintf('Unable to create migrations directory "%s".', $directory));
}
if (file_exists($path)) {
throw new RuntimeException(sprintf('Migration file "%s" already exists.', $path));
}
$code = $this->stub($className, $tableName);
if (file_put_contents($path, $code, \LOCK_EX) === \false) {
throw new RuntimeException(sprintf('Unable to write migration file "%s".', $path));
}
return $path;
}
private function stub(string $className, ?string $tableName): string
{
$up = '';
$down = '';
if ($tableName !== null && $tableName !== '') {
$up = sprintf(<<<'PHP'
$sql = "CREATE TABLE `{$wpdb->prefix}%s` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) {$this->collation()};";
dbDelta($sql);
PHP
, $tableName);
$down = sprintf(<<<'PHP'
$wpdb->query("DROP TABLE IF EXISTS `{$wpdb->prefix}%s`");
PHP
, $tableName);
}
return sprintf(<<<'PHP'
<?php
declare(strict_types=1);
namespace %s;
use JooosiFon\Database\Migration\AbstractMigration;
/**
* Auto-generated migration. Update the description and implementation.
*/
final class %s extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(): void
{
global $wpdb;
%s
}
public function down(): void
{
global $wpdb;
%s
}
}
PHP
, $this->configuration->namespace(), $className, $up, $down);
}
}
@@ -0,0 +1,80 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use RuntimeException;
/**
* Moves legacy migration history to the current table and namespace.
*
* @todo Remove this legacy rebrand upgrader completely in Jooosi Fon 3.0.0.
*/
final class MigrationHistoryUpgrader
{
public function upgrade(string $legacyTableName, string $tableName, string $legacyNamespace, string $namespace): void
{
global $wpdb;
$legacyTable = $wpdb->prefix . $legacyTableName;
$table = $wpdb->prefix . $tableName;
$legacyTableExists = $this->tableExists($legacyTable);
$tableExists = $this->tableExists($table);
if ($legacyTableExists && !$tableExists) {
$this->renameTable($legacyTable, $table);
$tableExists = \true;
} elseif ($legacyTableExists) {
$this->mergeTables($legacyTable, $table);
$this->dropTable($legacyTable);
}
if ($tableExists) {
$this->migrateNamespace($table, $legacyNamespace, $namespace);
}
}
private function renameTable(string $legacyTable, string $table): void
{
global $wpdb;
if ($wpdb->query("RENAME TABLE `{$legacyTable}` TO `{$table}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to rename the Jooosi Fon migrations table.');
}
}
private function mergeTables(string $legacyTable, string $table): void
{
global $wpdb;
$merged = $wpdb->query("INSERT IGNORE INTO `{$table}` (`version`, `executed_at`, `execution_time`)\n SELECT `version`, `executed_at`, `execution_time` FROM `{$legacyTable}`");
if ($merged === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to merge the legacy Jooosi Fon migration history.');
}
}
private function dropTable(string $legacyTable): void
{
global $wpdb;
if ($wpdb->query("DROP TABLE `{$legacyTable}`") === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to remove the legacy Jooosi Fon migrations table.');
}
}
private function migrateNamespace(string $table, string $legacyNamespace, string $namespace): void
{
global $wpdb;
$like = $wpdb->esc_like($legacyNamespace) . '%';
$legacyVersion = $wpdb->get_var($wpdb->prepare("SELECT `version` FROM `{$table}` WHERE `version` LIKE %s LIMIT 1", $like));
if (!is_string($legacyVersion)) {
return;
}
$inserted = $wpdb->query($wpdb->prepare("INSERT IGNORE INTO `{$table}` (`version`, `executed_at`, `execution_time`)\n SELECT REPLACE(`version`, %s, %s), `executed_at`, `execution_time`\n FROM `{$table}` WHERE `version` LIKE %s", $legacyNamespace, $namespace, $like));
if ($inserted === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to migrate the Jooosi Fon migration namespace.');
}
$deleted = $wpdb->query($wpdb->prepare("DELETE FROM `{$table}` WHERE `version` LIKE %s", $like));
if ($deleted === \false) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to clean up the legacy Jooosi Fon migration namespace.');
}
}
/**
* @phpstan-impure
*/
private function tableExists(string $table): bool
{
global $wpdb;
$foundTable = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table)));
return is_string($foundTable) && $foundTable === $table;
}
}
@@ -0,0 +1,77 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
/**
* Coordinates migration discovery, persistence, execution, and CLI access.
*/
final class MigrationManager
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
private \JooosiFon\Database\Migration\MigrationRegistry $registry;
private \JooosiFon\Database\Migration\MigrationRepository $repository;
private \JooosiFon\Database\Migration\MigrationGenerator $generator;
/**
* @param array<string, string> $configuration
*/
public function __construct(array $configuration = [])
{
$this->configuration = new \JooosiFon\Database\Migration\MigrationConfiguration($configuration);
$this->registry = new \JooosiFon\Database\Migration\MigrationRegistry($this->configuration);
$this->repository = new \JooosiFon\Database\Migration\MigrationRepository($this->configuration, $this->registry);
$this->generator = new \JooosiFon\Database\Migration\MigrationGenerator($this->configuration);
}
public function boot(): void
{
if (!function_exists('dbDelta')) {
require_once \ABSPATH . 'wp-admin/includes/upgrade.php';
}
if (class_exists('WP_CLI')) {
\WP_CLI::add_command($this->configuration->commandNamespace(), new \JooosiFon\Database\Migration\MigrationCommand($this));
}
}
public function install(): void
{
$this->repository->install();
}
public function generate(?string $tableName = null): string
{
return $this->generator->generate($tableName);
}
/**
* @return array<string, array{version: string, executed: bool, executed_at: ?string, execution_time: ?int}>
*/
public function list(): array
{
return $this->repository->versions();
}
/**
* @return list<array{version: string, executed_at: string, execution_time: int}>
*/
public function execute(): array
{
$this->install();
$versions = $this->list();
$definitions = [];
foreach ($this->registry->all() as $definition) {
$definitions[$definition->version] = $definition;
}
$executed = [];
foreach ($versions as $version) {
if ($version['executed'] || !isset($definitions[$version['version']])) {
continue;
}
$definition = $definitions[$version['version']];
$migration = $this->registry->create($definition->className);
$startedAt = microtime(\true);
$migration->preUp();
$migration->up();
$migration->postUp();
$executionTime = (int) round((microtime(\true) - $startedAt) * 1000);
$this->repository->recordExecution($definition, $executionTime);
$executed[] = ['version' => $definition->version, 'executed_at' => function_exists('current_time') ? current_time('mysql') : gmdate('Y-m-d H:i:s'), 'execution_time' => $executionTime];
}
return $executed;
}
}
@@ -0,0 +1,56 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use RuntimeException;
/**
* Discovers migrations from the configured directory.
*/
final class MigrationRegistry
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
public function __construct(\JooosiFon\Database\Migration\MigrationConfiguration $configuration)
{
$this->configuration = $configuration;
}
/**
* @return list<MigrationDefinition>
*/
public function all(): array
{
$files = glob($this->configuration->migrationsPath() . \DIRECTORY_SEPARATOR . 'Version*.php');
if (!is_array($files)) {
return [];
}
sort($files, \SORT_STRING);
$definitions = [];
foreach ($files as $file) {
require_once $file;
$className = $this->configuration->namespace() . '\\' . pathinfo($file, \PATHINFO_FILENAME);
if (!class_exists($className)) {
throw new RuntimeException(sprintf('Migration class "%s" could not be loaded from "%s".', $className, $file));
}
$migration = new $className();
if (!$migration instanceof \JooosiFon\Database\Migration\AbstractMigration) {
throw new RuntimeException(sprintf('Migration class "%s" must extend %s.', $className, \JooosiFon\Database\Migration\AbstractMigration::class));
}
$definitions[] = new \JooosiFon\Database\Migration\MigrationDefinition($className, $migration->getDescription());
}
return $definitions;
}
public function create(string $className): \JooosiFon\Database\Migration\AbstractMigration
{
if (!class_exists($className)) {
$this->all();
}
if (!class_exists($className)) {
throw new RuntimeException(sprintf('Migration class "%s" could not be loaded.', $className));
}
$migration = new $className();
if (!$migration instanceof \JooosiFon\Database\Migration\AbstractMigration) {
throw new RuntimeException(sprintf('Migration class "%s" must extend %s.', $className, \JooosiFon\Database\Migration\AbstractMigration::class));
}
return $migration;
}
}
@@ -0,0 +1,95 @@
<?php
declare (strict_types=1);
namespace JooosiFon\Database\Migration;
use RuntimeException;
/**
* Persists and reads migration execution history.
*/
final class MigrationRepository
{
private \JooosiFon\Database\Migration\MigrationConfiguration $configuration;
private \JooosiFon\Database\Migration\MigrationRegistry $registry;
public function __construct(\JooosiFon\Database\Migration\MigrationConfiguration $configuration, \JooosiFon\Database\Migration\MigrationRegistry $registry)
{
$this->configuration = $configuration;
$this->registry = $registry;
}
public function install(): void
{
if ($this->tableExists()) {
return;
}
global $wpdb;
$collation = $wpdb->has_cap('collation') ? $wpdb->get_charset_collate() : '';
$tableName = $this->tableName();
$sql = "CREATE TABLE `{$tableName}` (\n `version` VARCHAR(191) NOT NULL,\n `executed_at` DATETIME DEFAULT NULL,\n `execution_time` INT DEFAULT NULL,\n PRIMARY KEY (`version`)\n ) {$collation};";
dbDelta($sql);
if (!$this->tableExists()) {
throw new RuntimeException($wpdb->last_error ?: 'Unable to create the Jooosi Fon migrations table.');
}
}
/**
* @return list<array<string, mixed>>
*/
public function metadata(): array
{
if (!$this->tableExists()) {
return [];
}
global $wpdb;
$results = $wpdb->get_results(sprintf('SELECT * FROM `%s`', $this->tableName()), \ARRAY_A);
if (!is_array($results)) {
return [];
}
$prefix = $this->configuration->namespace() . '\\';
return array_values(array_filter($results, static function (array $result) use ($prefix): bool {
$version = isset($result['version']) ? (string) $result['version'] : '';
return strncmp($version, $prefix, strlen($prefix)) === 0;
}));
}
/**
* @return array<string, array{version: string, executed: bool, executed_at: ?string, execution_time: ?int}>
*/
public function versions(): array
{
$versions = [];
foreach ($this->registry->all() as $definition) {
$versions[$definition->version] = ['version' => $definition->version, 'executed' => \false, 'executed_at' => null, 'execution_time' => null];
}
foreach ($this->metadata() as $metadata) {
$version = (string) $metadata['version'];
$versions[$version] = ['version' => $version, 'executed' => \true, 'executed_at' => isset($metadata['executed_at']) ? (string) $metadata['executed_at'] : null, 'execution_time' => isset($metadata['execution_time']) ? (int) $metadata['execution_time'] : null];
}
ksort($versions, \SORT_STRING);
return $versions;
}
public function recordExecution(\JooosiFon\Database\Migration\MigrationDefinition $definition, int $executionTime): void
{
global $wpdb;
$inserted = $wpdb->insert($this->tableName(), ['version' => $definition->version, 'executed_at' => $this->timestamp(), 'execution_time' => max(0, $executionTime)], ['%s', '%s', '%d']);
if ($inserted === \false) {
throw new RuntimeException($wpdb->last_error ?: sprintf('Unable to record migration "%s".', $definition->version));
}
}
public function tableName(): string
{
global $wpdb;
return $wpdb->prefix . $this->configuration->tableName();
}
/**
* @phpstan-impure
*/
private function tableExists(): bool
{
global $wpdb;
$tableName = $this->tableName();
$foundTable = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($tableName)));
return is_string($foundTable) && $foundTable === $tableName;
}
private function timestamp(): string
{
return function_exists('current_time') ? current_time('mysql') : gmdate('Y-m-d H:i:s');
}
}