Completed
Push — master ( bc87d5...f777a6 )
by Nicolas
03:58
created

SeedCommand::getSeederName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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