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: | |
17: | |
18: | |
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: | |
33: | |
34: | |
35: | |
36: | |
37: | public function __construct(Resolver $resolver) |
38: | { |
39: | parent::__construct(); |
40: | |
41: | $this->resolver = $resolver; |
42: | } |
43: | |
44: | |
45: | |
46: | |
47: | |
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: | |
78: | |
79: | |
80: | |
81: | protected function getSeeder(InputInterface $input) |
82: | { |
83: | $class = $input->getOption('class') ?? \DatabaseSeeder::class; |
84: | |
85: | return new $class(); |
86: | } |
87: | |
88: | |
89: | |
90: | |
91: | |
92: | |
93: | protected function getDatabase(InputInterface $input) |
94: | { |
95: | $database = $input->getOption('database'); |
96: | |
97: | return $database ?: $this->resolver->getDefaultConnection(); |
98: | } |
99: | } |
100: | |