Passed
Pull Request — master (#15)
by Richard
06:30
created

ArtomatorControllerCommand::handle()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 22
rs 9.5555
cc 5
nc 4
nop 0
1
<?php
2
3
namespace PWWEB\Artomator\Commands;
4
5
use InvalidArgumentException;
6
use PWWEB\Artomator\Artomator;
7
use Laracasts\Generators\Migrations\SchemaParser;
8
use PWWEB\Artomator\Migrations\SyntaxBuilder;
9
use Symfony\Component\Console\Input\InputOption;
10
11
class ArtomatorControllerCommand extends Artomator
12
{
13
    /**
14
     * The console command name.
15
     *
16
     * @var string
17
     */
18
    protected $name = 'artomator:controller';
19
20
    /**
21
     * The console command description.
22
     *
23
     * @var string
24
     */
25
    protected $description = 'Create a new controller class';
26
27
    /**
28
     * The type of class being generated.
29
     *
30
     * @var string
31
     */
32
    protected $type = 'Controller';
33
34
    /**
35
     * The default stub file to be used.
36
     *
37
     * @var string
38
     */
39
    protected $stub = 'controller.model.stub';
40
41
    /**
42
     * Get the stub file for the generator.
43
     *
44
     * @return string
45
     */
46
    protected function getStub()
47
    {
48
        $path = base_path() . config('artomator.stubPath');
49
        $path = $path . $this->stub;
50
51
        if (file_exists($path) === true) {
52
            return $path;
53
        } else {
54
            return __DIR__ . '/Stubs/' . $this->stub;
55
        }
56
    }
57
58
    /**
59
     * Get the default namespace for the class.
60
     *
61
     * @param string $rootNamespace The class name to return the namespace for.
62
     *
63
     * @return string
64
     */
65
    protected function getDefaultNamespace($rootNamespace)
66
    {
67
        return $rootNamespace . '\Http\Controllers';
68
    }
69
70
    public function handle()
71
    {
72
        $name = $this->getNameInput();
73
        $name .= preg_match('/Controller$/', $name) ? "" : "Controller";
74
75
        $className = $this->qualifyClass($name);
76
        $path = $this->getPath($className);
77
        // First we will check to see if the class already exists. If it does, we don't want
78
        // to create the class and overwrite the user's code. So, we will bail out so the
79
        // code is untouched. Otherwise, we will continue generating this class' files.
80
        if ((!$this->hasOption('force') ||
81
             !$this->option('force')) &&
82
             $this->alreadyExists($name)) {
83
            $this->error($this->type . ' already exists!');
84
            return false;
85
        }
86
        // Next, we will generate the path to the location where this class' file should get
87
        // written. Then, we will build the class and make the proper replacements on the
88
        // stub files so that it gets the correctly formatted namespace and class name.
89
        $this->makeDirectory($path);
90
        $this->files->put($path, $this->buildClass($className));
91
        $this->info($this->type . ' created successfully.');
92
    }
93
94
    /**
95
     * Build the class with the given name.
96
     *
97
     * Remove the base controller import if we are already in base namespace.
98
     *
99
     * @param string $name The model name to build.
100
     *
101
     * @return string
102
     */
103
    protected function buildClass($name)
104
    {
105
        $controllerNamespace = $this->getNamespace($name);
106
107
        $replace = [];
108
109
        // if ($this->option('parent')) {
110
        //     $replace = $this->buildParentReplacements();
111
        // }
112
        $replace = $this->buildSchemaReplacements($replace);
113
        $replace = $this->buildModelReplacements($replace);
114
115
        $replace["use {$controllerNamespace}\Controller;\n"] = '';
116
117
        return str_replace(
118
            array_keys($replace),
119
            array_values($replace),
120
            parent::buildClass($name)
121
        );
122
    }
123
124
    /**
125
     * Build the schema replacement values.
126
     *
127
     * @param array $replace The existing replacements to append to.
128
     *
129
     * @return array
130
     */
131
    protected function buildSchemaReplacements(array $replace)
132
    {
133
        if ($this->option('schema') !== null) {
134
            $schema = $this->option('schema');
135
            $schema = (new SchemaParser())->parse($schema);
0 ignored issues
show
Bug introduced by
It seems like $schema can also be of type string[]; however, parameter $schema of Laracasts\Generators\Mig...s\SchemaParser::parse() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
            $schema = (new SchemaParser())->parse(/** @scrutinizer ignore-type */ $schema);
Loading history...
136
            $syntax = new SyntaxBuilder();
137
            $data = $syntax->createDataSchema($schema);
138
        } else {
139
            $data = "";
140
        }
141
142
        return array_merge(
143
            $replace,
144
            [
145
            '{{schema_data}}' => $data,
146
            ]
147
        );
148
    }
149
150
    /**
151
     * Build the model replacement values.
152
     *
153
     * @param array $replace The existing replacements to append to.
154
     *
155
     * @return array
156
     */
157
    protected function buildModelReplacements(array $replace = [])
158
    {
159
        if (is_null($this->option('model')) === true) {
160
            $this->modelClass = $this->parseModel((string) $this->getNameInput());
161
            $modelName = $this->getNameInput();
162
            $this->requestClass = $this->parseRequest((string) $this->getNameInput());
163
        } else {
164
            $this->modelClass = $this->parseModel((string) $this->option('model'));
165
            $modelName = $this->option('model');
166
            $this->requestClass = $this->parseRequest((string) $this->option('model'));
167
        }
168
169
        if (class_exists($this->modelClass) === false) {
170
            if ($this->confirm("A {$this->modelClass} model does not exist. Do you want to generate it?", true) === true) {
171
                $this->call('artomator:model', [
172
                    'name' => $modelName,
173
                ]);
174
            } else {
175
                $this->stub = 'controller.stub';
176
            }
177
        }
178
179
        return parent::buildModelReplacements($replace);
180
    }
181
182
    /**
183
     * Get the console command options.
184
     *
185
     * @return array
186
     */
187
    protected function getOptions()
188
    {
189
        return [
190
            ['model', 'm', InputOption::VALUE_REQUIRED, 'Generate a resource controller for the given model.'],
191
            ['resource', 'r', InputOption::VALUE_NONE, 'Generate a resource controller class.'],
192
            ['invokable', 'i', InputOption::VALUE_NONE, 'Generate a single method, invokable controller class.'],
193
            ['parent', 'p', InputOption::VALUE_OPTIONAL, 'Generate a nested resource controller class.'],
194
            ['api', null, InputOption::VALUE_NONE, 'Exclude the create and edit methods from the controller.'],
195
            ['schema', 's', InputOption::VALUE_OPTIONAL, 'Optional schema to be attached to the migration', null],
196
        ];
197
    }
198
}
199