Completed
Push — master ( 6e27f1...d5fec2 )
by Nicolas
03:36
created

SeedCommand::moduleSeed()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
nc 8
nop 1
dl 0
loc 23
ccs 0
cts 15
cp 0
crap 56
rs 8.6186
c 0
b 0
f 0
1
<?php
2
3
namespace Nwidart\Modules\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Contracts\Debug\ExceptionHandler;
7
use Illuminate\Support\Str;
8
use Nwidart\Modules\Contracts\RepositoryInterface;
9
use Nwidart\Modules\Module;
10
use Nwidart\Modules\Support\Config\GenerateConfigReader;
11
use Nwidart\Modules\Traits\ModuleCommandTrait;
12
use RuntimeException;
13
use Symfony\Component\Console\Input\InputArgument;
14
use Symfony\Component\Console\Input\InputOption;
15
16
class SeedCommand extends Command
17
{
18
    use ModuleCommandTrait;
19
20
    /**
21
     * The console command name.
22
     *
23
     * @var string
24
     */
25
    protected $name = 'module:seed';
26
27
    /**
28
     * The console command description.
29
     *
30
     * @var string
31
     */
32
    protected $description = 'Run database seeder from the specified module or from all modules.';
33
34
    /**
35
     * Execute the console command.
36
     * @throws FatalThrowableError
37
     */
38
    public function handle()
39
    {
40
        try {
41
            if ($name = $this->argument('module')) {
42
                $name = Str::studly($name);
43
                $this->moduleSeed($this->getModuleByName($name));
44
            } else {
45
                $modules = $this->getModuleRepository()->getOrdered();
46
                array_walk($modules, [$this, 'moduleSeed']);
47
                $this->info('All modules seeded.');
48
            }
49
        } catch (\Throwable $e) {
50
            $this->reportException($e);
51
52
            $this->renderException($this->getOutput(), $e);
53
54
            return 1;
55
        }
56
    }
57
58
    /**
59
     * @throws RuntimeException
60
     * @return RepositoryInterface
61
     */
62
    public function getModuleRepository(): RepositoryInterface
63
    {
64
        $modules = $this->laravel['modules'];
65
        if (!$modules instanceof RepositoryInterface) {
66
            throw new RuntimeException('Module repository not found!');
67
        }
68
69
        return $modules;
70
    }
71
72
    /**
73
     * @param $name
74
     *
75
     * @throws RuntimeException
76
     *
77
     * @return Module
78
     */
79
    public function getModuleByName($name)
80
    {
81
        $modules = $this->getModuleRepository();
82
        if ($modules->has($name) === false) {
83
            throw new RuntimeException("Module [$name] does not exists.");
84
        }
85
86
        return $modules->find($name);
87
    }
88
89
    /**
90
     * @param Module $module
91
     *
92
     * @return void
93
     */
94
    public function moduleSeed(Module $module)
95
    {
96
        $seeders = [];
97
        $name = $module->getName();
0 ignored issues
show
Bug introduced by
Consider using $module->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
98
        $config = $module->get('migration');
99
        if (is_array($config) && array_key_exists('seeds', $config)) {
100
            foreach ((array)$config['seeds'] as $class) {
101
                if (class_exists($class)) {
102
                    $seeders[] = $class;
103
                }
104
            }
105
        } else {
106
            $class = $this->getSeederName($name); //legacy support
107
            if (class_exists($class)) {
108
                $seeders[] = $class;
109
            }
110
        }
111
112
        if (count($seeders) > 0) {
113
            array_walk($seeders, [$this, 'dbSeed']);
114
            $this->info("Module [$name] seeded.");
115
        }
116
    }
117
118
    /**
119
     * Seed the specified module.
120
     *
121
     * @param string $className
122
     */
123
    protected function dbSeed($className)
124
    {
125
        $params = [
126
            '--class' => $className,
127
        ];
128
129
        if ($option = $this->option('database')) {
130
            $params['--database'] = $option;
131
        }
132
133
        if ($option = $this->option('force')) {
134
            $params['--force'] = $option;
135
        }
136
137
        $this->call('db:seed', $params);
138
    }
139
140
    /**
141
     * Get master database seeder name for the specified module.
142
     *
143
     * @param string $name
144
     *
145
     * @return string
146
     */
147
    public function getSeederName($name)
148
    {
149
        $name = Str::studly($name);
150
151
        $namespace = $this->laravel['modules']->config('namespace');
152
        $seederPath = GenerateConfigReader::read('seeder');
153
        $seederPath = str_replace('/', '\\', $seederPath->getPath());
154
155
        return $namespace . '\\' . $name . '\\' . $seederPath . '\\' . $name . 'DatabaseSeeder';
156
    }
157
158
    /**
159
     * Report the exception to the exception handler.
160
     *
161
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
162
     * @param  \Throwable  $e
163
     * @return void
164
     */
165
    protected function renderException($output, \Throwable $e)
166
    {
167
        $this->laravel[ExceptionHandler::class]->renderForConsole($output, $e);
168
    }
169
170
    /**
171
     * Report the exception to the exception handler.
172
     *
173
     * @param  \Throwable  $e
174
     * @return void
175
     */
176
    protected function reportException(\Throwable $e)
177
    {
178
        $this->laravel[ExceptionHandler::class]->report($e);
179
    }
180
181
    /**
182
     * Get the console command arguments.
183
     *
184
     * @return array
185
     */
186 92
    protected function getArguments()
187
    {
188
        return [
189 92
            ['module', InputArgument::OPTIONAL, 'The name of module will be used.'],
190
        ];
191
    }
192
193
    /**
194
     * Get the console command options.
195
     *
196
     * @return array
197
     */
198 92 View Code Duplication
    protected function getOptions()
199
    {
200
        return [
201 92
            ['class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder.'],
202
            ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed.'],
203
            ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'],
204
        ];
205
    }
206
}
207