Files
ulthon_admin/extend/base/common/command/scheme/Sync.php

95 lines
3.2 KiB
PHP

<?php
namespace base\common\command\scheme;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use app\common\service\scheme\SchemeToDbService;
use app\common\scheme\attribute\Table;
use ReflectionClass;
class Sync extends Command
{
protected function configure()
{
$this->setName('scheme:sync')
->addOption('skip-data', null, Option::VALUE_NONE, 'Skip data migration')
->addOption('force', null, Option::VALUE_NONE, 'Force execution without confirmation')
->setDescription('Synchronize Scheme classes to Database');
}
protected function execute(Input $input, Output $output)
{
$skipData = $input->getOption('skip-data');
$service = new SchemeToDbService();
$schemeDir = app()->getAppPath() . 'admin/scheme/';
$ignoreTables = Config::get('scheme.ignore_tables', []);
$connection = Config::get('database.default', 'mysql');
$prefix = Config::get('database.connections.' . $connection . '.prefix', '');
if (!is_dir($schemeDir)) {
$output->writeln("<error>Scheme directory not found: $schemeDir</error>");
return;
}
$files = glob($schemeDir . '*.php');
foreach ($files as $file) {
require_once $file;
$className = 'app\\admin\\scheme\\' . basename($file, '.php');
if (class_exists($className)) {
$tableName = $this->getTableNameFromScheme($className);
if (!empty($tableName) && $this->isIgnoredTable($tableName, $ignoreTables, $prefix)) {
$output->writeln("Skipping $className (ignored table: $tableName)");
continue;
}
$output->writeln("Syncing $className...");
try {
$backup = $service->sync($className, $skipData);
$output->writeln("<info>Success!</info>");
if ($backup) {
$output->writeln("Backup created: $backup");
}
} catch (\Exception $e) {
$output->writeln("<error>Failed: " . $e->getMessage() . "</error>");
}
}
}
}
protected function getTableNameFromScheme(string $className): string
{
try {
$ref = new ReflectionClass($className);
$tableAttrs = $ref->getAttributes(Table::class);
if (empty($tableAttrs)) {
return '';
}
$tableAttr = $tableAttrs[0]->newInstance();
return (string)($tableAttr->name ?? '');
} catch (\Throwable $e) {
return '';
}
}
protected function isIgnoredTable(string $tableName, array $ignoreTables, string $prefix): bool
{
if (empty($ignoreTables)) {
return false;
}
$shortName = $tableName;
if ($prefix && str_starts_with($tableName, $prefix)) {
$shortName = substr($tableName, strlen($prefix));
}
return in_array($shortName, $ignoreTables, true) || in_array($tableName, $ignoreTables, true);
}
}