Completed
Push — master ( 0bff19...1b573a )
by Basil
02:06
created

ThemeController::actionCreate()   B

Complexity

Conditions 9
Paths 27

Size

Total Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 7.2298
c 0
b 0
f 0
cc 9
nc 27
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace luya\console\commands;
4
5
use luya\helpers\FileHelper;
6
use luya\helpers\Json;
7
use luya\theme\ThemeConfig;
8
use Yii;
9
use yii\helpers\Console;
10
use yii\helpers\Inflector;
11
12
/**
13
 * Command to create a new LUYA theme.
14
 *
15
 * @author Bennet Klarhoelter <[email protected]>
16
 * @since 1.0.21
17
 */
18
class ThemeController extends \luya\console\Command
19
{
20
    /**
21
     * @inheritdoc
22
     */
23
    public $defaultAction = 'create';
24
    
25
    /**
26
     * Create a new theme.
27
     *
28
     * @param string|null $themeName
29
     *
30
     * @return int
31
     * @throws \yii\base\Exception
32
     */
33
    public function actionCreate(string $themeName = null)
34
    {
35
        Console::clearScreenBeforeCursor();
36
    
37
        $themeName = $this->prompt("Enter the name (lower case) of the theme you like to generate:", ['default' => $themeName]);
38
        
39
        $newName = preg_replace("/[^a-z]/", "", strtolower($themeName));
40
        if ($newName !== $themeName) {
41
            if (!$this->confirm("We have changed the name to '{$newName}'. Do you want to proceed with this name?")) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->confirm("We have ...oceed with this name?") of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
42
                return $this->outputError('Abort by user.');
43
            } else {
44
                $themeName = $newName;
45
            }
46
        }
47
    
48
        $availableModules = implode(', ', array_column(Yii::$app->getFrontendModules(), 'id'));
49
        $themeLocation = $this->prompt("Enter the theme location where to generate (as path alias e.g. app, $availableModules):", ['default' => 'app']);
50
        $themeLocation = '@' . ltrim($themeLocation, '@');
51
    
52
        preg_match("#^@[A-z]+#", $themeLocation, $newThemeLocation);
53
54
        if ($newThemeLocation[0] !== $themeLocation) {
55
            if (!$this->confirm("We have changed the name to '{$newThemeLocation[0]}'. Do you want to proceed with this name?")) {
56
                return $this->outputError('Abort by user.');
57
            } else {
58
                $themeLocation = $newThemeLocation[0];
59
            }
60
        }
61
        
62
        $basePath = $themeLocation . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . $themeName;
63
        $themeFolder = Yii::getAlias($basePath);
64
    
65
        if (file_exists($themeFolder)) {
66
            return $this->outputError("The folder " . $themeFolder . " exists already.");
67
        }
68
    
69
        $this->outputInfo("Theme path alias: " . $basePath);
70
        $this->outputInfo("Theme real path: " . $themeFolder);
71
        if (!$this->confirm("Do you want continue?")) {
72
            return $this->outputError('Abort by user.');
73
        }
74
        
75
        $folders = [
76
            '',
77
            'resources',
78
            'views',
79
            'views/layouts',
80
            'views/cmslayouts',
81
        ];
82
83
        foreach ($folders as $folder) {
84
            FileHelper::createDirectory($themeFolder . DIRECTORY_SEPARATOR . $folder);
85
        }
86
        
87
        $contents = [
88
            $themeFolder. DIRECTORY_SEPARATOR . 'theme.json' => $this->renderJson($basePath, $themeName),
89
        ];
90
        
91
        foreach ($contents as $fileName => $content) {
92
            FileHelper::writeFile($fileName, $content);
93
        }
94
        
95
        return $this->outputSuccess("Theme files has been created successfully. Please run `".$_SERVER['PHP_SELF']." import` to loaded into the database.");
96
    }
97
    
98
    /**
99
     * Render the json template.
100
     *
101
     * @param string $basePath
102
     * @param string $themeName
103
     * @return string
104
     */
105
    private function renderJson(string $basePath, string $themeName)
106
    {
107
        $themeConfig = new ThemeConfig($basePath, []);
108
        $themeConfig->name = $themeName;
109
        
110
        if ($this->confirm('Inherit from other theme?')) {
111
            $themeConfig->parentTheme = $this->prompt("Enter the base path (e.g. `@app/themes/blank`) of the parent theme:",
112
                [
113
                    'default' => null,
114
                    'validator' => [$this, 'validateParentTheme'],
115
                ]);
116
        }
117
        
118
        return Json::encode($themeConfig->toArray(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
119
    }
120
121
    private function validateParentTheme($input, &$error)
122
    {
123
        if (!preg_match('/^@[a-z]+$/', $input)) {
124
            $error = 'The theme name must be only letter chars!';
125
            return false;
126
        } elseif (Yii::getAlias($input, false) === false) {
127
            $error = 'The theme base path not exists!';
128
            return false;
129
        }
130
131
        return true;
132
    }
133
}
134