1: <?php
2:
3: namespace Aurora\System\Console\Commands\Seeds;
4:
5: use Symfony\Component\Console\Command\Command;
6: use Illuminate\Database\ConnectionResolverInterface as Resolver;
7: use Illuminate\Database\Eloquent\Model;
8: use Symfony\Component\Console\Input\InputInterface;
9: use Symfony\Component\Console\Input\InputOption;
10: use Symfony\Component\Console\Output\OutputInterface;
11: use Symfony\Component\Console\Question\ConfirmationQuestion;
12:
13: class SeedCommand extends Command
14: {
15: /**
16: * The connection resolver instance.
17: *
18: * @var \Illuminate\Database\ConnectionResolverInterface
19: */
20: protected $resolver;
21:
22: protected function configure(): void
23: {
24: $this->setName('db:seed')
25: ->setDescription('Seed the database with records')
26: ->addOption('class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder')
27: ->addOption('database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed')
28: ->addOption('force', null, InputOption::VALUE_OPTIONAL, 'Force the operation to run when in production');
29: }
30:
31: /**
32: * Create a new database seed command instance.
33: *
34: * @param \Illuminate\Database\ConnectionResolverInterface $resolver
35: * @return void
36: */
37: public function __construct(Resolver $resolver)
38: {
39: parent::__construct();
40:
41: $this->resolver = $resolver;
42: }
43:
44: /**
45: * Execute the console command.
46: *
47: * @return int
48: */
49: protected function execute(InputInterface $input, OutputInterface $output): int
50: {
51: $defaultAnswer = $input->getOption('no-interaction');
52: if (!$input->getOption('force')) {
53: $helper = $this->getHelper('question');
54: $question = new ConfirmationQuestion('Do you really wish to run this command? (Y/N)', $defaultAnswer);
55: if (!$helper->ask($input, $output, $question)) {
56: return Command::SUCCESS;
57: }
58: }
59:
60: $previousConnection = $this->resolver->getDefaultConnection();
61:
62: $this->resolver->setDefaultConnection($this->getDatabase($input));
63:
64: Model::unguarded(function () use ($input) {
65: $this->getSeeder($input)->__invoke();
66: });
67:
68: if ($previousConnection) {
69: $this->resolver->setDefaultConnection($previousConnection);
70: }
71:
72: $output->writeln('Database seeding completed successfully.');
73:
74: return Command::SUCCESS;
75: }
76:
77: /**
78: * Get a seeder instance from the container.
79: *
80: * @return \Illuminate\Database\Seeder
81: */
82: protected function getSeeder(InputInterface $input)
83: {
84: $class = $input->getOption('class') ?? \DatabaseSeeder::class;
85:
86: return new $class();
87: }
88:
89: /**
90: * Get the name of the database connection to use.
91: *
92: * @return string
93: */
94: protected function getDatabase(InputInterface $input)
95: {
96: $database = $input->getOption('database');
97:
98: return $database ?: $this->resolver->getDefaultConnection();
99: }
100: }
101: