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: if (!$input->getOption('force')) {
52: $helper = $this->getHelper('question');
53: $question = new ConfirmationQuestion('Do you really wish to run this command? (Y/N)', false);
54: if (!$helper->ask($input, $output, $question)) {
55: return Command::SUCCESS;
56: }
57: }
58:
59: $previousConnection = $this->resolver->getDefaultConnection();
60:
61: $this->resolver->setDefaultConnection($this->getDatabase($input));
62:
63: Model::unguarded(function () use ($input) {
64: $this->getSeeder($input)->__invoke();
65: });
66:
67: if ($previousConnection) {
68: $this->resolver->setDefaultConnection($previousConnection);
69: }
70:
71: $output->writeln('Database seeding completed successfully.');
72:
73: return Command::SUCCESS;
74: }
75:
76: /**
77: * Get a seeder instance from the container.
78: *
79: * @return \Illuminate\Database\Seeder
80: */
81: protected function getSeeder(InputInterface $input)
82: {
83: $class = $input->getOption('class') ?? \DatabaseSeeder::class;
84:
85: return new $class();
86: }
87:
88: /**
89: * Get the name of the database connection to use.
90: *
91: * @return string
92: */
93: protected function getDatabase(InputInterface $input)
94: {
95: $database = $input->getOption('database');
96:
97: return $database ?: $this->resolver->getDefaultConnection();
98: }
99: }
100: