RepositoryMakeCommand::bindingsHandle()   A
last analyzed

Complexity

Conditions 2
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 11
rs 10
1
<?php
2
3
namespace Modules\Core\Console;
4
5
use Illuminate\Contracts\Filesystem\FileNotFoundException;
6
use Illuminate\Support\Facades\File;
7
use Illuminate\Support\Str;
8
use Nwidart\Modules\Commands\GeneratorCommand;
9
use Nwidart\Modules\Exceptions\FileAlreadyExistException;
10
use Nwidart\Modules\Generators\FileGenerator;
11
use Nwidart\Modules\Support\Config\GenerateConfigReader;
12
use Nwidart\Modules\Support\Stub;
13
use Nwidart\Modules\Traits\ModuleCommandTrait;
14
use Symfony\Component\Console\Input\InputArgument;
15
use Symfony\Component\Console\Input\InputOption;
16
17
class RepositoryMakeCommand extends GeneratorCommand
18
{
19
    use ModuleCommandTrait;
20
21
    /**
22
     * The name of argument name.
23
     *
24
     * @var string
25
     */
26
    protected $argumentName = 'name';
27
28
    /**
29
     * The console command name.
30
     *
31
     * @var string
32
     */
33
    protected $name = 'module:make-repository';
34
35
    /**
36
     * The console command description.
37
     *
38
     * @var string
39
     */
40
    protected $description = 'Generate new Repository for the specified module.';
41
42
    public function getDefaultNamespace(): string
43
    {
44
        /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $laravelFileRepository */
45
        $laravelFileRepository = $this->laravel['modules'];
46
47
        return $laravelFileRepository->config('paths.generator.repository.path', 'Repositories');
48
    }
49
50
    /**
51
     * Get the console command arguments.
52
     *
53
     * @return array
54
     */
55
    protected function getArguments()
56
    {
57
        return [
58
            ['name', InputArgument::REQUIRED, 'The name of the repository.'],
59
            ['module', InputArgument::OPTIONAL, 'The name of module will be used.'],
60
        ];
61
    }
62
63
    /**
64
     * Get the console command options.
65
     *
66
     * @return array
67
     */
68
    protected function getOptions()
69
    {
70
        return [
71
            ['model', null, InputOption::VALUE_OPTIONAL, 'The model that should be assigned.', null],
72
            ['resource', 'r', InputOption::VALUE_NONE, 'Flag to create associated resource', null],
73
            ['presenter', 'p', InputOption::VALUE_NONE, 'Flag to create associated presenter', null],
74
        ];
75
    }
76
77
    private function handleOptionalResourceOption()
78
    {
79
        if ($this->option('resource') === true) {
80
            $resourceName = $this->getModelName().'Transformer';
81
82
            $this->call('module:make-resource', [
83
                'name' => $resourceName, 'module' => $this->argument('module'),
84
            ]);
85
        }
86
    }
87
88
    private function handleOptionalPresenterOption()
89
    {
90
        if ($this->option('presenter') === true) {
91
            $presenterName = $this->getModelName().'Presenter';
92
93
            $this->call('module:make-presenter', [
94
                'name' => $presenterName, 'module' => $this->argument('module'),
95
            ]);
96
        }
97
    }
98
99
    /**
100
     * @param $path
101
     *
102
     * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException
103
     */
104
    private function bindingsHandle($path)
105
    {
106
        $contents = $this->getBindingsTemplateContents();
107
108
        try {
109
            $contents = str_replace('//', $contents, File::get($path));
110
            File::replace($path, $contents);
111
112
            $this->info("Update : {$path}");
113
        } catch (FileNotFoundException $e) {
114
            $this->error("File : {$path} not found.");
115
        }
116
    }
117
118
    /**
119
     * Get bindings template contents.
120
     *
121
     * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException
122
     *
123
     * @return string
124
     */
125
    protected function getBindingsTemplateContents()
126
    {
127
        /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $laravelFileRepository */
128
        $laravelFileRepository = $this->laravel['modules'];
129
        $module = $laravelFileRepository->findOrFail($this->getModuleName());
130
131
        return (new Stub('/bindings.stub', [
132
            'NAMESPACE'       => $this->getClassNamespace($module),
133
            'INTERFACE_CLASS' => $this->getClass(),
134
            'IMPLEMENT_CLASS' => $this->getClass().'Eloquent',
135
            'PLACEHOLDER'     => '//',
136
        ]))->render();
137
    }
138
139
    /**
140
     * Get implementation template contents.
141
     *
142
     * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException
143
     *
144
     * @return string
145
     */
146
    protected function getImplementTemplateContents()
147
    {
148
        /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $laravelFileRepository */
149
        $laravelFileRepository = $this->laravel['modules'];
150
        $module = $laravelFileRepository->findOrFail($this->getModuleName());
151
152
        $root_namespace = $laravelFileRepository->config('namespace');
153
        $root_namespace .= '\\'.$module->getStudlyName();
154
155
        return (new Stub('/repository-eloquent.stub', [
156
            'MODEL'          => $this->getModelName(),
157
            'NAMESPACE'      => $this->getClassNamespace($module),
158
            'CLASS'          => $this->getClass(),
159
            'ROOT_NAMESPACE' => $root_namespace,
160
        ]))->render();
161
    }
162
163
    /**
164
     * Get interface template contents.
165
     *
166
     * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException
167
     *
168
     * @return string
169
     */
170
    protected function getInterfaceTemplateContents()
171
    {
172
        /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $laravelFileRepository */
173
        $laravelFileRepository = $this->laravel['modules'];
174
        $module = $laravelFileRepository->findOrFail($this->getModuleName());
175
176
        return (new Stub('/repository.stub', [
177
            'NAMESPACE' => $this->getClassNamespace($module),
178
            'CLASS'     => $this->getClass(),
179
        ]))->render();
180
    }
181
182
    /**
183
     * @return string
184
     */
185
    private function getModelName()
186
    {
187
        return (string) $this->option('model')
188
            ?: Str::before(class_basename((string) $this->argument($this->argumentName)), 'Repository');
189
    }
190
191
    /**
192
     * @return mixed
193
     */
194
    protected function getDestinationFilePath()
195
    {
196
        /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $laravelFileRepository */
197
        $laravelFileRepository = $this->laravel['modules'];
198
        $path = $laravelFileRepository->getModulePath($this->getModuleName());
199
        $repositoryPath = GenerateConfigReader::read('repository');
200
201
        return $path.$repositoryPath->getPath().'/'.$this->getFileName().'.php';
202
    }
203
204
    /**
205
     * @return string
206
     */
207
    private function getFileName()
208
    {
209
        return Str::studly((string) $this->argument('name'));
210
    }
211
212
    /**
213
     * Execute the console command.
214
     *
215
     * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException
216
     */
217
    public function handle()
218
    {
219
        $path = str_replace('\\', '/', $this->getDestinationFilePath());
220
        $this->interfaceHandle($path);
221
222
        $path = Str::before($path, '.php').'Eloquent.php';
223
        $this->implementationHandle($path);
224
225
        $path = module_path($this->getModuleName()).'/Providers/RepositoryServiceProvider.php';
226
        $this->bindingsHandle($path);
227
228
        $this->handleOptionalResourceOption();
229
        $this->handleOptionalPresenterOption();
230
    }
231
232
    /**
233
     * Execute the console interface command.
234
     *
235
     * @param $path
236
     *
237
     * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException
238
     */
239
    protected function interfaceHandle($path)
240
    {
241
        /** @var \Illuminate\Filesystem\Filesystem $filesystem */
242
        $filesystem = $this->laravel['files'];
243
        if (!$filesystem->isDirectory($dir = dirname($path))) {
244
            $filesystem->makeDirectory($dir, 0777, true);
245
        }
246
247
        $contents = $this->getInterfaceTemplateContents();
248
249
        try {
250
            with(new FileGenerator($path, $contents))->generate();
251
252
            $this->info("Created : {$path}");
253
        } catch (FileAlreadyExistException $e) {
254
            $this->error("File : {$path} already exists.");
255
        }
256
    }
257
258
    /**
259
     * Execute the console implementation command.
260
     *
261
     * @param $path
262
     *
263
     * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException
264
     */
265
    protected function implementationHandle($path)
266
    {
267
        /** @var \Illuminate\Filesystem\Filesystem $filesystem */
268
        $filesystem = $this->laravel['files'];
269
        if (!$filesystem->isDirectory($dir = dirname($path))) {
270
            $filesystem->makeDirectory($dir, 0777, true);
271
        }
272
273
        $contents = $this->getImplementTemplateContents();
274
275
        try {
276
            with(new FileGenerator($path, $contents))->generate();
277
278
            $this->info("Created : {$path}");
279
        } catch (FileAlreadyExistException $e) {
280
            $this->error("File : {$path} already exists.");
281
        }
282
    }
283
284
    /**
285
     * Get template contents.
286
     *
287
     * @return string
288
     */
289
    protected function getTemplateContents()
290
    {
291
        return '';
292
    }
293
}
294