91 lines
3.1 KiB
PHP
Executable File
91 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;
|
|
|
|
class DbSeedCommand extends Command
|
|
{
|
|
protected static $defaultName = 'db:seed';
|
|
protected static $defaultDescription = 'Executa as classes de seeder';
|
|
|
|
protected function configure(): void
|
|
{
|
|
$this
|
|
->addArgument('class', InputArgument::OPTIONAL, 'O nome da classe seeder específica para rodar');
|
|
}
|
|
|
|
protected function execute(InputInterface $input, OutputInterface $output): int
|
|
{
|
|
$className = $input->getArgument('class');
|
|
$seedersPath = dirname(__DIR__, 3) . '/database/seeders';
|
|
|
|
if (!is_dir($seedersPath)) {
|
|
$output->writeln('<error>Diretório de seeders não encontrado.</error>');
|
|
return Command::FAILURE;
|
|
}
|
|
|
|
if ($className) {
|
|
return $this->runSeeder($className, $seedersPath, $output);
|
|
}
|
|
|
|
// Se não especificou classe, tenta rodar o DatabaseSeeder ou todos os arquivos .php
|
|
$dbSeederFile = $seedersPath . '/DatabaseSeeder.php';
|
|
if (file_exists($dbSeederFile)) {
|
|
return $this->runSeeder('DatabaseSeeder', $seedersPath, $output);
|
|
}
|
|
|
|
$files = glob($seedersPath . '/*.php');
|
|
if (empty($files)) {
|
|
$output->writeln('<info>Nenhum seeder encontrado.</info>');
|
|
return Command::SUCCESS;
|
|
}
|
|
|
|
foreach ($files as $file) {
|
|
$name = basename($file, '.php');
|
|
if ($name === 'DatabaseSeeder') continue; // Já rodamos se existisse
|
|
$this->runSeeder($name, $seedersPath, $output);
|
|
}
|
|
|
|
return Command::SUCCESS;
|
|
}
|
|
|
|
protected function runSeeder(string $name, string $path, OutputInterface $output): int
|
|
{
|
|
$file = $path . '/' . $name . '.php';
|
|
|
|
if (!file_exists($file)) {
|
|
$output->writeln("<error>Seeder não encontrado: {$name}</error>");
|
|
return Command::FAILURE;
|
|
}
|
|
|
|
$output->write("Rodando seeder: <info>{$name}</info>... ");
|
|
|
|
try {
|
|
require_once $file;
|
|
|
|
if (class_exists($name)) {
|
|
$seeder = new $name();
|
|
if (method_exists($seeder, 'run')) {
|
|
$seeder->run();
|
|
$output->writeln('<info>OK</info>');
|
|
return Command::SUCCESS;
|
|
} else {
|
|
$output->writeln('<comment>Método run() não encontrado.</comment>');
|
|
return Command::FAILURE;
|
|
}
|
|
} else {
|
|
$output->writeln("<error>Classe {$name} não encontrada no arquivo.</error>");
|
|
return Command::FAILURE;
|
|
}
|
|
} catch (\Exception $e) {
|
|
$output->writeln("<error>FALHA</error>");
|
|
$output->writeln("<error>Erro: " . $e->getMessage() . "</error>");
|
|
return Command::FAILURE;
|
|
}
|
|
}
|
|
}
|