Passed
Push — master ( 74ddc4...4602de )
by Mohammad
03:46
created

Generator::getEntity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Shamaseen\Repository\Generator\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Database\Eloquent\Model;
0 ignored issues
show
Bug introduced by
The type Illuminate\Database\Eloquent\Model was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Illuminate\Support\Facades\File;
8
use ReflectionClass;
9
use Shamaseen\Repository\Generator\Forms\formGenerator;
10
11
/**
12
 * Class RepositoryGenerator
13
 * @package Shamaseen\Repository\Generator\Commands
14
 */
15
class Generator extends Command
16
{
17
    /**
18
     * The name and signature of the console command.
19
     *
20
     * @var string
21
     */
22
    protected $signature = 'make:repository
23
    {name : Class (singular) for example User} {--only-view}';
24
25
    /**
26
     * The console command description.
27
     *
28
     * @var string
29
     */
30
    protected $description = 'Create repository generator';
31
32
    /**
33
     * The repository name.
34
     *
35
     * @var string
36
     */
37
    protected $repoName;
38
    /**
39
     * The repository name space.
40
     *
41
     * @var string
42
     */
43
    protected $repoNamespace;
44
    private $formGenerator;
45
46
    /**
47
     * Create a new command instance.
48
     *
49
     */
50
    public function __construct()
51
    {
52
        parent::__construct();
53
        $this->formGenerator = new formGenerator();
54
    }
55
56
    /**
57
     * Execute the console command.
58
     *
59
     * @throws \ReflectionException
60
     */
61
    public function handle()
62
    {
63
        $file = preg_split( " (/|\\\\) ", (string)$this->argument('name')) ?? [];
64
        $this->repoName = $file[count($file) - 1];
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, 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

64
        $this->repoName = $file[count(/** @scrutinizer ignore-type */ $file) - 1];
Loading history...
65
66
        unset($file[count($file) - 1]);
67
        $path = implode("\\", $file);
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $pieces of implode() does only seem to accept array, 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

67
        $path = implode("\\", /** @scrutinizer ignore-type */ $file);
Loading history...
68
69
        if($this->option('only-view'))
70
        {
71
            $this->makeViewsAndLanguage($path);
72
            return null;
73
        }
74
75
        $this->makeRepositoryPatternFiles($path);
76
    }
77
78
    function makeRepositoryPatternFiles($path)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
79
    {
80
        $model= str_plural(\Config::get('repository.model'));
81
        $interface= str_plural(\Config::get('repository.interface'));
82
        $repository= str_plural(\Config::get('repository.repository'));
83
84
        $this->generate($path, \Config::get('repository.controllers_folder'), 'Controller');
85
        $this->generate($path, $model, 'Entity');
86
        $this->generate($path, \Config::get('repository.requests_folder'), 'Request');
87
        $this->generate($path, $interface, 'Interface');
88
        $this->generate($path, $repository, 'Repository');
89
90
        File::append(\Config::get('repository.route_path') . '/web.php', "\n" . 'Route::resource(\'' . strtolower(str_plural($this->repoName)) . "', '".$path."\\".$this->repoName."Controller');");
91
    }
92
93
    /**
94
     * @param $path
95
     * @throws \ReflectionException
96
     */
97
    function makeViewsAndLanguage($path)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
98
    {
99
        $entity = $this->getEntity($path);
100
101
        $createHtml = '';
102
        $editHtml = '';
103
        if($entity instanceof Model)
104
        {
105
            $createHtml = $this->formGenerator->generateForm($entity);
106
            $editHtml = $this->formGenerator->generateForm($entity,'put');
107
        }
108
        else
109
        {
110
            if(!$this->confirm('There is no entity for '.$this->repoName.", do you want to continue (this will disable form generator) ?"))
111
            {
112
                echo "Dispatch ..";
113
                die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
114
            }
115
        }
116
117
        foreach (\Config::get('repository.languages') as $lang)
118
        {
119
            $this->generate(lcfirst($this->repoName),\Config::get('repository.lang_path')."/{$lang}" , 'lang');
120
        }
121
        $this->generate(lcfirst($this->repoName),\Config::get('repository.resources_path')."/views" , 'create',$createHtml);
122
        $this->generate(lcfirst($this->repoName),\Config::get('repository.resources_path')."/views" , 'edit',$editHtml);
123
        $this->generate(lcfirst($this->repoName),\Config::get('repository.resources_path')."/views" , 'index');
124
        $this->generate(lcfirst($this->repoName),\Config::get('repository.resources_path')."/views" , 'show');
125
    }
126
127
    /**
128
     * @param $path
129
     * @return bool|Model|object
130
     * @throws \ReflectionException
131
     */
132
    function getEntity($path)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
133
    {
134
        $myClass = 'App\Entities\\'.$path."\\".$this->repoName;
135
        if(!class_exists($myClass))
136
            return false;
137
138
        $refl = new ReflectionClass($myClass);
139
140
        return $refl->newInstance();
141
    }
142
143
    /**
144
     * Get stub content to generate needed files
145
     *
146
     * @param string $type determine which stub should choose to get content
147
     * @return false|string
148
     */
149
    protected function getStub($type)
150
    {
151
        return file_get_contents(\Config::get('repository.stubs_path') . "/$type.stub");
152
    }
153
154
    /**
155
     * @param string $path Class path
156
     * @param string $folder default path to generate in
157
     * @param string $type define which kind of files should generate
158
     * @param string $form
159
     * @return bool
160
     */
161
    protected function generate($path, $folder, $type,$form ='')
162
    {
163
        $content = $this->getStub($type);
164
165
        if($content === false)
166
        {
167
            echo 'file '.$type.".stub is not exist !";
168
            return false;
169
        }
170
171
        $template = str_replace(
172
            [
173
                '{{modelName}}',
174
                "{{folder}}",
175
                "{{path}}",
176
                "{{modelBaseFolderName}}",
177
                "{{interfaceBaseFolderName}}",
178
                "{{form}}",
179
            ],
180
            [
181
                $this->repoName,
182
                str_plural($folder),
183
                $path,
184
                str_plural(\Config::get('repository.model','Entity')),
185
                str_plural(\Config::get('repository.interface','Interface')),
186
                $form
187
            ],
188
            $this->getStub($type)
189
        );
190
191
        $folder = str_replace('\\','/',$folder);
192
        $path = str_replace('\\','/',$path);
193
        
194
        switch ($type)
195
        {
196
            case 'Entity':
197
                $filePath = $this->getFolderOrCreate(\Config::get('repository.app_path') . "/{$folder}/{$path}");
198
                $filePath = rtrim($filePath,'/');
199
                $filePath .= "/";
200
                file_put_contents($filePath . "{$this->repoName}.php", $template);
201
                break;
202
            case 'Controller':
203
            case 'Request':
204
            case 'Repository':
205
            case 'Interface':
206
                $filePath = $this->getFolderOrCreate(\Config::get('repository.app_path') . "/{$folder}/{$path}");
207
                $filePath = rtrim($filePath,'/');
208
                $filePath .= "/";
209
                file_put_contents($filePath . "{$this->repoName}{$type}.php", $template);
210
                break;
211
            case 'create':
212
            case 'edit':
213
            case 'index':
214
            case 'show':
215
                $filePath = $this->getFolderOrCreate($folder."/".str_plural($path))."/";
216
                $repoName = lcfirst($type);
217
                file_put_contents($filePath . $repoName.".blade.php", $template);
218
            break;
219
            default:
220
                $filePath = $this->getFolderOrCreate($folder)."/";
221
                $repoName = lcfirst($this->repoName);
222
                file_put_contents($filePath . $repoName.".php", $template);
223
        }
224
        return true;
225
    }
226
227
    /**
228
     * Check if folder exist
229
     * @param string $path class path
230
     * @return string
231
     */
232
    public function getFolderOrCreate($path)
233
    {
234
        if (!file_exists($path)) {
235
            mkdir($path, 0777, true);
236
        }
237
        return $path;
238
    }
239
}
240