Completed
Push — master ( 48aefa...87bdd5 )
by Andrii
03:08
created

Starter   C

Complexity

Total Complexity 59

Size/Duplication

Total Lines 318
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 1 Features 1
Metric Value
wmc 59
lcom 1
cbo 10
dl 0
loc 318
ccs 0
cts 215
cp 0
rs 6.1904
c 3
b 1
f 1

22 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A noProject() 0 5 1
A startProject() 0 10 1
C getConfig() 0 35 8
A readConfig() 0 10 2
A getGoals() 0 4 1
A loadEnv() 0 7 2
A loadGoals() 0 7 2
A includeGoals() 0 9 2
A readYaml() 0 4 1
B addAliases() 0 20 9
A hasAlias() 0 6 2
D requireAll() 0 28 9
A updateDotHidev() 0 6 2
A passthru() 0 8 1
B needsComposerInstall() 0 27 3
A includeAll() 0 9 1
A moreConfig() 0 9 3
A setRootDir() 0 4 1
A getRootDir() 0 8 2
A findRootDir() 0 11 3
A buildRootPath() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like Starter often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Starter, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Automation tool mixed with code generator for easier continuous development
4
 *
5
 * @link      https://github.com/hiqdev/hidev
6
 * @package   hidev
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hidev\base;
12
13
use hidev\components\Request;
14
use hidev\helpers\ConfigPlugin;
15
use hidev\helpers\FileHelper;
16
use Symfony\Component\Yaml\Yaml;
17
use Yii;
18
use yii\base\InvalidParamException;
19
use yii\helpers\ArrayHelper;
20
21
/**
22
 * Application starter.
23
 * Chdirs to the project's root directory and loads dependencies and configs.
24
 *
25
 * XXX it's important to distinguish:
26
 * - goals definitions (hidev config) - YAML files
27
 * - application config - PHP files
28
 */
29
class Starter
30
{
31
    /**
32
     * @var string absolute path to the project root directory
33
     */
34
    private $_rootDir;
35
36
    /**
37
     * @var array goals definitions
38
     */
39
    private $goals = [];
40
41
    /**
42
     * @var array application config files
43
     */
44
    private $appFiles = ['@hidev/config/basis.php'];
45
46
    /**
47
     * Make action.
48
     */
49
    public function __construct()
50
    {
51
        $request = new Request();
52
        $this->scriptFile = $request->getScriptFile();
0 ignored issues
show
Bug introduced by
The property scriptFile does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
53
        $route = reset($request->resolve());
0 ignored issues
show
Bug introduced by
$request->resolve() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
54
        $id = reset(explode('/', $route, 2));
0 ignored issues
show
Bug introduced by
explode('/', $route, 2) cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
55
        if (in_array($id, ['init'], true)) {
56
            $this->noProject();
57
        } else {
58
            $this->startProject();
59
        }
60
    }
61
62
    public function noProject()
63
    {
64
        $this->setRootDir(getcwd());
65
        $this->addAliases();
66
    }
67
68
    public function startProject()
69
    {
70
        $this->getRootDir();
71
        $this->loadEnv();
72
        $this->loadGoals();
73
        $this->addAliases();
74
        $this->requireAll();
75
        $this->includeAll();
76
        $this->moreConfig();
77
    }
78
79
    public function getConfig()
80
    {
81
        $config = ArrayHelper::merge($this->readConfig(), [
82
            'components' => $this->goals,
83
        ]);
84
85
        $config['components']['request']['scriptFile'] = $this->scriptFile;
86
        unset($config['components']['include']);
87
        unset($config['components']['plugins']);
88
89
        foreach ($config['components'] as $id => $def) {
90
            if (empty($def['class'])) {
91
                unset($config['components'][$id]);
92
                $controllers[$id] = $def;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$controllers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $controllers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
93
            }
94
        }
95
        if (!empty($controllers)) {
96
            $config = ArrayHelper::merge($config, [
97
                'controllerMap' => $controllers,
98
            ]);
99
        }
100
101
        if (!empty($config['controllerMap'])) {
102
            foreach ($config['controllerMap'] as &$def) {
103
                if (is_array($def) && empty($def['class'])) {
104
                    $def['class'] = \hidev\controllers\CommonController::class;
105
                }
106
            }
107
        }
108
109
        $interpolator = new Interpolator();
110
        $interpolator->interpolate($config);
111
112
        return $config;
113
    }
114
115
    public function readConfig()
116
    {
117
        $config = [];
118
        foreach ($this->appFiles as $file) {
119
            $path = Yii::getAlias($file);
120
            $config = ArrayHelper::merge($config, require $path);
121
        }
122
123
        return $config;
124
    }
125
126
    public function getGoals()
127
    {
128
        return $this->goals;
129
    }
130
131
    private function loadEnv()
132
    {
133
        if (class_exists(\Dotenv\Dotenv::class)) {
134
            $dotenv = new \Dotenv\Dotenv('.');
135
            $dotenv->load();
136
        }
137
    }
138
139
    private function loadGoals()
140
    {
141
        $this->includeGoals('hidev.yml');
142
        if (file_exists('hidev-local.yml')) {
143
            $this->includeGoals('hidev-local.yml');
144
        }
145
    }
146
147
    private function includeGoals($paths)
148
    {
149
        foreach ((array) $paths as $path) {
150
            $this->goals = ArrayHelper::merge(
151
                $this->goals,
152
                $this->readYaml($path)
153
            );
154
        }
155
    }
156
157
    private function readYaml($path)
158
    {
159
        return Yaml::parse(FileHelper::read($path));
160
    }
161
162
    /**
163
     * Adds aliases:
164
     * - @root alias to current project root dir
165
     * - @hidev own alias
166
     * - current package namespace for it could be used from hidev
167
     * - aliases listed in config.
168
     */
169
    private function addAliases()
170
    {
171
        Yii::setAlias('@root', $this->getRootDir());
172
        Yii::setAlias('@hidev', dirname(__DIR__));
173
174
        $package = $this->goals['package'];
175
        $alias  = isset($package['namespace']) ? strtr($package['namespace'], '\\', '/') : '';
176
        if ($alias && !Yii::getAlias('@' . $alias, false)) {
177
            $srcdir = Yii::getAlias('@root/' . ($package['src'] ?: 'src'));
178
            Yii::setAlias($alias, $srcdir);
0 ignored issues
show
Bug introduced by
It seems like $srcdir defined by \Yii::getAlias('@root/' ...ckage['src'] ?: 'src')) on line 177 can also be of type boolean; however, yii\BaseYii::setAlias() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
179
        }
180
        $aliases = $this->goals['aliases'];
181
        if (!empty($aliases) && is_array($aliases)) {
182
            foreach ($aliases as $alias => $path) {
183
                if (!$this->hasAlias($alias)) {
184
                    Yii::setAlias($alias, $path);
185
                }
186
            }
187
        }
188
    }
189
190
    private function hasAlias($alias, $exact = true)
0 ignored issues
show
Unused Code introduced by
The parameter $exact is not used and could be removed.

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

Loading history...
191
    {
192
        $pos = strpos($alias, '/');
193
194
        return $pos === false ? isset(Yii::$aliases[$alias]) : isset(Yii::$aliases[substr($alias, 0, $pos)][$alias]);
195
    }
196
197
    /**
198
     * - install configured plugins and register their app config
199
     * - install project dependencies and register
200
     * - register application config files.
201
     */
202
    private function requireAll()
203
    {
204
        $vendors = [];
205
        $plugins = $this->goals['plugins'];
206
        if ($plugins) {
207
            $file = File::create('.hidev/composer.json');
208
            $data = ArrayHelper::merge($file->load(), ['require' => $plugins]);
209
            if ($file->save($data) || !is_dir('.hidev/vendor')) {
210
                $this->updateDotHidev();
211
            }
212
            $vendors[] = $this->buildRootPath('.hidev/vendor');
213
        }
214
        if ($this->needsComposerInstall()) {
215
            if ($this->passthru('composer', ['install', '--ansi'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->passthru('compose...y('install', '--ansi')) of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
216
                throw new InvalidParamException('Failed initialize project with composer install');
217
            }
218
        }
219
        $vendors[] = $this->buildRootPath('vendor');
220
221
        foreach ($vendors as $vendor) {
222
            foreach (['console', 'hidev'] as $name) {
223
                $path = ConfigPlugin::path($name, $vendor);
224
                if (file_exists($path)) {
225
                    $this->appFiles[] = $path;
226
                }
227
            }
228
        }
229
    }
230
231
    /**
232
     * Update action.
233
     * @return int exit code
234
     */
235
    public function updateDotHidev()
236
    {
237
        if (file_exists('.hidev/composer.json')) {
238
            return $this->passthru('composer', ['update', '-d', '.hidev', '--prefer-source', '--ansi']);
239
        }
240
    }
241
242
    /**
243
     * Passthru command.
244
     * @param string $command
245
     * @param array $args
246
     * @return int exit code
247
     */
248
    private function passthru($command, $args)
249
    {
250
        $binary = new BinaryPhp([
251
            'name' => $command,
252
        ]);
253
254
        return $binary->passthru($args);
255
    }
256
257
    private function needsComposerInstall()
258
    {
259
        if (file_exists('vendor')) {
260
            return false;
261
        }
262
        if (!file_exists('composer.json')) {
263
            return false;
264
        }
265
266
        return true;
267
268
    /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
269
        $data = File::create('composer.json')->load();
270
        foreach (['require', 'require-dev'] as $key) {
271
            if (isset($data[$key])) {
272
                foreach ($data[$key] as $package => $version) {
273
                    list(, $name) = explode('/', $package);
274
                    if (strncmp($name, 'hidev-', 6) === 0) {
275
                        return true;
276
                    }
277
                }
278
            }
279
        }
280
281
        return false;
282
    */
283
    }
284
285
    /**
286
     * Include all configured includes.
287
     */
288
    private function includeAll()
289
    {
290
        $config = $this->readConfig();
291
        $files = array_merge(
292
            (array) $this->goals['include'],
293
            (array) $config['components']['include']
294
        );
295
        $this->includeGoals($files);
296
    }
297
298
    /**
299
     * Registers more application config to load.
300
     */
301
    private function moreConfig()
302
    {
303
        $paths = $this->goals['config'];
304
        foreach ((array) $paths as $path) {
305
            if ($path) {
306
                $this->appFiles[] = $path;
307
            }
308
        }
309
    }
310
311
    public function setRootDir($value)
312
    {
313
        $this->_rootDir = $value;
314
    }
315
316
    public function getRootDir()
317
    {
318
        if ($this->_rootDir === null) {
319
            $this->_rootDir = $this->findRootDir();
320
        }
321
322
        return $this->_rootDir;
323
    }
324
325
    /**
326
     * Chdirs to project's root by looking for config file in the current directory and up.
327
     * @throws InvalidParamException when failed to find
328
     * @return string path to the root directory of hidev project
329
     */
330
    private function findRootDir()
331
    {
332
        $configFile = 'hidev.yml';
333
        for ($i = 0; $i < 9; ++$i) {
334
            if (file_exists($configFile)) {
335
                return getcwd();
336
            }
337
            chdir('..');
338
        }
339
        throw new InvalidParamException("Not a hidev project (or any of the parent directories).\nUse `hidev init` to initialize hidev project.");
340
    }
341
342
    public function buildRootPath($subpath)
343
    {
344
        return $this->getRootDir() . DIRECTORY_SEPARATOR . $subpath;
345
    }
346
}
347