Passed
Push — develop ( c66d22...ba64a1 )
by nguereza
03:53
created

MakeCrudActionCommand::getMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
rs 10
1
<?php
2
3
/**
4
 * Platine PHP
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant
7
 * PHP Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine PHP
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file MakeCrudActionCommand.php
34
 *
35
 *  The Command to generate new CRUD action class
36
 *
37
 *  @package    Platine\Framework\Console\Command
38
 *  @author Platine Developers team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Framework\Console\Command;
49
50
use Platine\Console\Input\Reader;
51
use Platine\Console\Output\Writer;
52
use Platine\Filesystem\Filesystem;
53
use Platine\Framework\App\Application;
54
use Platine\Stdlib\Helper\Json;
55
use Platine\Stdlib\Helper\Str;
56
57
/**
58
 * @class MakeCrudActionCommand
59
 * @package Platine\Framework\Console\Command
60
 */
61
class MakeCrudActionCommand extends MakeResourceActionCommand
62
{
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected string $type = 'crud';
67
68
    /**
69
     * Create new instance
70
     * @param Application $application
71
     * @param Filesystem $filesystem
72
     */
73
    public function __construct(
74
        Application $application,
75
        Filesystem $filesystem
76
    ) {
77
        parent::__construct($application, $filesystem);
78
        $this->setName('make:crud')
79
              ->setDescription('Command to generate platine CRUD action');
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function interact(Reader $reader, Writer $writer): void
86
    {
87
        parent::interact($reader, $writer);
88
89
        // Load configuration file if exist
90
        $this->loadConfig();
91
92
        $this->recordResourceClasses();
93
    }
94
95
     /**
96
     * {@inheritdoc}
97
     */
98
    public function getClassTemplate(): string
99
    {
100
        return <<<EOF
101
        <?php
102
        
103
        declare(strict_types=1);
104
        
105
        namespace %namespace%;
106
        
107
        use Platine\Framework\Helper\Flash;
108
        use Platine\Framework\Http\Action\CrudAction;
109
        use Platine\Framework\Http\RouteHelper;
110
        use Platine\Lang\Lang;
111
        use Platine\Logger\LoggerInterface;
112
        use Platine\Pagination\Pagination;
113
        use Platine\Template\Template;
114
        %uses%
115
116
        /**
117
        * @class %classname%
118
        * @package %namespace%
119
        * @extends CrudAction<%base_entity_class%>
120
        */
121
        class %classname% extends CrudAction
122
        {
123
            
124
            %attributes%
125
        
126
            /**
127
            * Create new instance
128
            * {@inheritdoc}
129
            * @param %base_repository% \$repository
130
            */
131
            public function __construct(
132
                Lang \$lang,
133
                Pagination \$pagination,
134
                Template \$template,
135
                Flash \$flash,
136
                RouteHelper \$routeHelper,
137
                LoggerInterface \$logger,
138
                %base_repository% \$repository
139
            ) {
140
                parent::__construct(
141
                    \$lang,
142
                    \$pagination,
143
                    \$template,
144
                    \$flash,
145
                    \$routeHelper,
146
                    \$logger
147
                );
148
                \$this->repository = \$repository;
149
            }
150
        }
151
        
152
        EOF;
153
    }
154
155
    /**
156
     * Record the resource classes
157
     * @return void
158
     */
159
    protected function recordResourceClasses(): void
160
    {
161
        $io = $this->io();
162
163
        $paramClass = $io->prompt('Enter the form parameter full class name', null);
164
        while (!class_exists($paramClass)) {
165
            $paramClass = $io->prompt('Class does not exists, please enter the form parameter full class name', null);
166
        }
167
168
        $this->paramClass = $paramClass;
169
170
        $validatorClass = $io->prompt('Enter the form validator full class name', null);
171
        while (!class_exists($validatorClass)) {
172
            $validatorClass = $io->prompt(
173
                'Class does not exists, please enter the form validator full class name',
174
                null
175
            );
176
        }
177
178
        $this->validatorClass = $validatorClass;
179
180
        $entityClass = $io->prompt('Enter the entity full class name', null);
181
        while (!class_exists($entityClass)) {
182
            $entityClass = $io->prompt('Class does not exists, please enter the entity full class name', null);
183
        }
184
185
        $this->entityClass = $entityClass;
186
187
        $repositoryClass = $io->prompt('Enter the repository full class name', null);
188
        while (!class_exists($repositoryClass)) {
189
            $repositoryClass = $io->prompt('Class does not exists, please enter the repository full class name', null);
190
        }
191
192
        $this->repositoryClass = $repositoryClass;
193
    }
194
195
    /**
196
     * {@inheritdoc}
197
     */
198
    protected function createClass(): string
199
    {
200
        $content = parent::createClass();
201
202
        $replace = '';
203
        $fields = $this->getFieldsPropertyBody($content);
204
        if (!empty($fields)) {
205
            $replace .= $fields;
206
        }
207
208
        return str_replace('%attributes%', $replace, $content);
209
    }
210
211
    /**
212
     * Return the fields property body
213
     * @param string $content
214
     * @return string
215
     */
216
    protected function getFieldsPropertyBody(string $content): string
0 ignored issues
show
Unused Code introduced by
The parameter $content is not used and could be removed. ( Ignorable by Annotation )

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

216
    protected function getFieldsPropertyBody(/** @scrutinizer ignore-unused */ string $content): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
217
    {
218
        $fields = $this->getOptionValue('fields');
219
        if ($fields === null) {
220
            return '';
221
        }
222
        $result = <<<EOF
223
        /**
224
            * {@inheritdoc}
225
            */
226
            protected array \$fields = ['name', 'description'];
227
        EOF;
228
229
        return $result;
230
    }
231
232
233
234
    /**
235
     * Return the template for order by
236
     * @return string
237
     */
238
    protected function getOrderByFieldsPropertyBody(): string
239
    {
240
        $result = '';
241
        $orderFields = $this->getOptionValue('fieldsOrder');
242
243
        if ($orderFields !== null) {
244
            $fields = (array) explode(',', $orderFields);
245
            $i = 1;
246
            foreach ($fields as $field) {
247
                $column = $field;
248
                $dir = 'ASC';
249
                $orderField = (array) explode(':', $field);
250
                if (isset($orderField[0])) {
251
                    $column = $orderField[0];
252
                }
253
254
                if (isset($orderField[1]) && in_array(strtolower($orderField[1]), ['asc', 'desc'])) {
255
                    $dir = $orderField[1];
256
                }
257
258
                $result .= ($i > 1 ? "\t\t\t\t\t    " : '') .
259
                        sprintf('->orderBy(\'%s\', \'%s\')', $column, Str::upper($dir)) .
260
                        (count($fields) > $i ? PHP_EOL : '');
261
                $i++;
262
            }
263
        }
264
265
        return $result;
266
    }
267
268
    /**
269
     * {@inheritdoc}
270
     */
271
    protected function getUsesContent(): string
272
    {
273
        $uses = parent::getUsesContent();
274
275
        $uses .= $this->getUsesTemplate($this->entityClass);
276
        $uses .= $this->getUsesTemplate($this->paramClass);
277
        $uses .= $this->getUsesTemplate($this->validatorClass);
278
        $uses .= $this->getUsesTemplate($this->repositoryClass);
279
280
        return <<<EOF
281
        $uses
282
        EOF;
283
    }
284
285
    /**
286
     * Return the property name
287
     * @param class-string $value
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
288
     * @return string
289
     */
290
    protected function getPropertyName(string $value): string
291
    {
292
        if (!isset($this->properties[$value])) {
293
            return '';
294
        }
295
296
        return $this->properties[$value]['name'];
297
    }
298
299
300
    /**
301
     * Return the route prefix
302
     * @return string
303
     */
304
    protected function getTemplatePrefix(): string
305
    {
306
        $templatePrefix = $this->getOptionValue('templatePrefix');
307
        if ($templatePrefix === null) {
308
            $actionName = $this->getShortClassName($this->className);
309
            $templatePrefix = Str::snake(str_ireplace('action', '', $actionName));
0 ignored issues
show
Bug introduced by
It seems like str_ireplace('action', '', $actionName) can also be of type array; however, parameter $value of Platine\Stdlib\Helper\Str::snake() 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

309
            $templatePrefix = Str::snake(/** @scrutinizer ignore-type */ str_ireplace('action', '', $actionName));
Loading history...
310
        }
311
312
        return $templatePrefix;
313
    }
314
315
    /**
316
     * Return the entity context key
317
     * @param bool $isKey
318
     * @return string
319
     */
320
    protected function getEntityContextKey(bool $isKey = true): string
321
    {
322
        $key = (string) $this->getOptionValue('entityContextKey');
323
        if (!empty($key)) {
324
            if ($isKey) {
325
                $key = Str::snake($key, '_');
326
            } else {
327
                $key = Str::camel($key, true);
328
            }
329
        }
330
331
        return $key;
332
    }
333
334
    /**
335
     * Return the route prefix
336
     * @return string
337
     */
338
    protected function getRoutePrefix(): string
339
    {
340
        $routePrefix = $this->getOptionValue('routePrefix');
341
        if ($routePrefix === null) {
342
            $actionName = $this->getShortClassName($this->className);
343
            $routePrefix = Str::snake(str_ireplace('action', '', $actionName));
0 ignored issues
show
Bug introduced by
It seems like str_ireplace('action', '', $actionName) can also be of type array; however, parameter $value of Platine\Stdlib\Helper\Str::snake() 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

343
            $routePrefix = Str::snake(/** @scrutinizer ignore-type */ str_ireplace('action', '', $actionName));
Loading history...
344
        }
345
346
        return $routePrefix;
347
    }
348
349
    /**
350
     * Return the message
351
     * @param string $option
352
     * @return string|null
353
     */
354
    protected function getMessage(string $option): ?string
355
    {
356
        $message = (string) $this->getOptionValue($option);
357
        if (!empty($message)) {
358
            $message = addslashes($message);
359
        }
360
361
        return $message;
362
    }
363
364
    /**
365
     * Load JSON configuration file if exist
366
     * @return void
367
     */
368
    protected function loadConfig(): void
369
    {
370
        $filename = $this->getOptionValue('config');
371
        if (!empty($filename)) {
372
            $file = $this->filesystem->file($filename);
373
            if ($file->exists() && $file->isReadable()) {
374
                $content = $file->read();
375
                /** @var array<string, string> $config */
376
                $config = Json::decode($content, true);
377
                foreach ($config as $option => $value) {
378
                    $optionKey = Str::camel($option, true);
379
                    $this->values[$optionKey] = $value;
380
                }
381
            }
382
        }
383
    }
384
}
385