Completed
Push — master ( d64abf...e41506 )
by Nicolas
03:10 queued 01:07
created

SeedCommand::renderException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
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\Module;
9
use Nwidart\Modules\Repository;
10
use Nwidart\Modules\Traits\ModuleCommandTrait;
11
use RuntimeException;
12
use Symfony\Component\Console\Input\InputArgument;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Debug\Exception\FatalThrowableError;
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);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type array; however, Illuminate\Support\Str::studly() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
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 (\Exception $e) {
50
            $e = new FatalThrowableError($e);
51
52
            $this->reportException($e);
53
54
            $this->renderException($this->getOutput(), $e);
55
56
            return 1;
57
        }
58
    }
59
60
    /**
61
     * @throws RuntimeException
62
     *
63
     * @return Repository
64
     */
65
    public function getModuleRepository()
66
    {
67
        $modules = $this->laravel['modules'];
68
        if (!$modules instanceof Repository) {
69
            throw new RuntimeException("Module repository not found!");
70
        }
71
72
        return $modules;
73
    }
74
75
    /**
76
     * @param $name
77
     *
78
     * @throws RuntimeException
79
     *
80
     * @return Module
81
     */
82
    public function getModuleByName($name)
83
    {
84
        $modules = $this->getModuleRepository();
85
        if ($modules->has($name) === false) {
86
            throw new RuntimeException("Module [$name] does not exists.");
87
        }
88
89
        return $modules->get($name);
0 ignored issues
show
Deprecated Code introduced by
The method Nwidart\Modules\Repository::get() has been deprecated.

This method has been deprecated.

Loading history...
90
    }
91
92
    /**
93
     * @param Module $module
94
     *
95
     * @return void
96
     */
97
    public function moduleSeed(Module $module)
98
    {
99
        $seeders = [];
100
        $name = $module->getName();
101
        $config = $module->get('migration');
102
        if (is_array($config) && array_key_exists('seeds', $config)) {
103
            foreach ((array)$config['seeds'] as $class) {
104
                if (class_exists($class)) {
105
                    $seeders[] = $class;
106
                }
107
            }
108
        } else {
109
            $class = $this->getSeederName($name); //legacy support
110
            if (class_exists($class)) {
111
                $seeders[] = $class;
112
            }
113
        }
114
115
        if (count($seeders) > 0) {
116
            array_walk($seeders, [$this, 'dbSeed']);
117
            $this->info("Module [$name] seeded.");
118
        }
119
    }
120
121
    /**
122
     * Seed the specified module.
123
     *
124
     * @param string $className
125
     */
126
    protected function dbSeed($className)
127
    {
128
        $params = [
129
            '--class' => $className,
130
        ];
131
132
        if ($option = $this->option('database')) {
133
            $params['--database'] = $option;
134
        }
135
136
        if ($option = $this->option('force')) {
137
            $params['--force'] = $option;
138
        }
139
140
        $this->call('db:seed', $params);
141
    }
142
143
    /**
144
     * Get master database seeder name for the specified module.
145
     *
146
     * @param string $name
147
     *
148
     * @return string
149
     */
150
    public function getSeederName($name)
151
    {
152
        $name = Str::studly($name);
153
154
        $namespace = $this->laravel['modules']->config('namespace');
155
156
        return $namespace . '\\' . $name . '\Database\Seeders\\' . $name . 'DatabaseSeeder';
157
    }
158
159
    /**
160
     * Report the exception to the exception handler.
161
     *
162
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
163
     * @param  \Exception  $e
164
     * @return void
165
     */
166
    protected function renderException($output, \Exception $e)
167
    {
168
        $this->laravel[ExceptionHandler::class]->renderForConsole($output, $e);
169
    }
170
171
    /**
172
     * Report the exception to the exception handler.
173
     *
174
     * @param  \Exception  $e
175
     * @return void
176
     */
177
    protected function reportException(\Exception $e)
178
    {
179
        $this->laravel[ExceptionHandler::class]->report($e);
180
    }
181
182
    /**
183
     * Get the console command arguments.
184
     *
185
     * @return array
186
     */
187 60
    protected function getArguments()
188
    {
189
        return [
190 60
            ['module', InputArgument::OPTIONAL, 'The name of module will be used.'],
191
        ];
192
    }
193
194
    /**
195
     * Get the console command options.
196
     *
197
     * @return array
198
     */
199 60
    protected function getOptions()
200
    {
201
        return [
202 60
            ['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