Files
dockerfluxodecaixapro/app/Console/Commands/ModuleDeleteCommand.php
T
2026-09-01 10:46:29 -03:00

88 lines
3.1 KiB
PHP
Executable File

<?php
namespace App\Console\Commands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Database\Capsule\Manager as Capsule;
class ModuleDeleteCommand extends Command
{
protected static $defaultName = 'module:delete';
protected static $defaultDescription = 'Remove fisicamente um módulo e suas tabelas associadas';
protected function configure(): void
{
$this
->addArgument('module', InputArgument::REQUIRED, 'O nome do módulo a ser removido')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Confirmar a remoção sem prompt');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$moduleName = $input->getArgument('module');
$force = $input->getOption('force');
$modulePath = dirname(__DIR__, 3) . '/modules/' . $moduleName;
if (!is_dir($modulePath)) {
$output->writeln("<error>Módulo '{$moduleName}' não encontrado em modules/.</error>");
return Command::FAILURE;
}
if (!$force) {
$output->writeln("<comment>Você tem certeza que deseja remover o módulo '{$moduleName}' e TODAS as suas tabelas associadas?</comment>");
$output->writeln("<info>Use a opção --force para confirmar.</info>");
return Command::FAILURE;
}
// 1. Drop associated tables if listed in module.json
$jsonPath = $modulePath . '/module.json';
if (file_exists($jsonPath)) {
$config = json_decode(file_get_contents($jsonPath), true);
if (isset($config['tables']) && is_array($config['tables'])) {
$output->writeln("<info>Limpando tabelas do banco de dados...</info>");
Capsule::connection()->statement('SET FOREIGN_KEY_CHECKS = 0');
foreach ($config['tables'] as $table) {
$output->write("Dropando tabela: <comment>{$table}</comment>... ");
Capsule::schema()->dropIfExists($table);
$output->writeln('<info>OK</info>');
}
Capsule::connection()->statement('SET FOREIGN_KEY_CHECKS = 1');
}
}
// 2. Remove files
$output->writeln("<info>Removendo arquivos do módulo...</info>");
$this->deleteDirectory($modulePath);
$output->writeln("<info>Módulo '{$moduleName}' removido com sucesso!</info>");
return Command::SUCCESS;
}
protected function deleteDirectory($dir): bool
{
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
}