79 lines
2.8 KiB
PHP
Executable File
79 lines
2.8 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 DbExportCommand extends Command
|
|
{
|
|
protected static $defaultName = 'db:export';
|
|
protected static $defaultDescription = 'Exporta os dados de uma tabela para CSV ou JSON';
|
|
|
|
protected function configure(): void
|
|
{
|
|
$this
|
|
->addArgument('table', InputArgument::REQUIRED, 'O nome da tabela')
|
|
->addOption('format', 'f', InputOption::VALUE_OPTIONAL, 'O formato do arquivo (csv, json)', 'csv')
|
|
->addOption('path', 'p', InputOption::VALUE_OPTIONAL, 'O caminho para salvar o arquivo', 'storage/exports');
|
|
}
|
|
|
|
protected function execute(InputInterface $input, OutputInterface $output): int
|
|
{
|
|
$tableName = $input->getArgument('table');
|
|
$format = strtolower($input->getOption('format'));
|
|
$path = $input->getOption('path');
|
|
|
|
$connection = Capsule::connection();
|
|
$dbName = $connection->getDatabaseName();
|
|
|
|
if (!Capsule::schema()->hasTable($tableName)) {
|
|
$output->writeln("<error>Tabela '{$tableName}' não encontrada no banco de dados.</error>");
|
|
return Command::FAILURE;
|
|
}
|
|
|
|
$results = $connection->table($tableName)->get();
|
|
|
|
if ($results->isEmpty()) {
|
|
$output->writeln("<info>A tabela '{$tableName}' está vazia.</info>");
|
|
return Command::SUCCESS;
|
|
}
|
|
|
|
$output->writeln("<info>Exportando dados da tabela: {$tableName}</info>");
|
|
|
|
$directory = dirname(__DIR__, 3) . '/' . ltrim($path, '/');
|
|
if (!is_dir($directory)) {
|
|
mkdir($directory, 0755, true);
|
|
}
|
|
|
|
$filename = "{$tableName}_" . date('Y-m-d_H-i-s') . ".{$format}";
|
|
$fullPath = rtrim($directory, '/') . '/' . $filename;
|
|
|
|
if ($format === 'json') {
|
|
file_put_contents($fullPath, json_encode($results, JSON_PRETTY_PRINT));
|
|
} elseif ($format === 'csv') {
|
|
$fp = fopen($fullPath, 'w');
|
|
|
|
// Adiciona o cabeçalho
|
|
$headers = array_keys((array) $results[0]);
|
|
fputcsv($fp, $headers);
|
|
|
|
foreach ($results as $row) {
|
|
fputcsv($fp, (array) $row);
|
|
}
|
|
|
|
fclose($fp);
|
|
} else {
|
|
$output->writeln("<error>Formato '{$format}' não suportado.</error>");
|
|
return Command::FAILURE;
|
|
}
|
|
|
|
$output->writeln("<info>Dados exportados com sucesso para: {$fullPath}</info>");
|
|
return Command::SUCCESS;
|
|
}
|
|
}
|