Completed
Push — master ( 375de1...c13e1e )
by Andrii
13:21
created

Starter::getConfig()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 32
rs 6.7272
cc 7
eloc 17
nc 6
nop 0
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)
27
 * - application config
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
    }
65
66
    public function startProject()
67
    {
68
        $this->getRootDir();
69
        $this->loadGoals();
70
        $this->addAliases();
71
        $this->requireAll();
72
        $this->includeAll();
73
        $this->moreConfig();
74
    }
75
76
    public function getConfig()
77
    {
78
        $config = ArrayHelper::merge($this->readConfig(), [
79
            'components' => $this->goals,
80
        ]);
81
82
        $config['components']['request']['scriptFile'] = $this->scriptFile;
83
        unset($config['components']['include']);
84
        unset($config['components']['plugins']);
85
86
        foreach ($config['components'] as $id => $def) {
87
            if (empty($def['class'])) {
88
                unset($config['components'][$id]);
89
                $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...
90
            }
91
        }
92
        $config = ArrayHelper::merge($config, [
93
            'controllerMap' => $controllers,
0 ignored issues
show
Bug introduced by
The variable $controllers does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
94
        ]);
95
96
        if (!empty($config['controllerMap'])) {
97
            foreach ($config['controllerMap'] as &$def) {
98
                if (is_array($def) && empty($def['class'])) {
99
                    $def['class'] = \hidev\controllers\CommonController::class;
100
                }
101
            }
102
        }
103
104
        // var_dump($config); die;
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
105
106
        return $config;
107
    }
108
109
    public function readConfig()
110
    {
111
        $config = [];
112
        foreach ($this->appFiles as $file) {
113
            $path = Yii::getAlias($file);
114
            $config = ArrayHelper::merge($config, require $path);
115
        }
116
117
        return $config;
118
    }
119
120
    public function getGoals()
121
    {
122
        return $this->goals;
123
    }
124
125
    private function loadGoals()
126
    {
127
        $this->includeGoals('hidev.yml');
128
        if (file_exists('hidev-local.yml')) {
129
            $this->includeGoals('hidev-local.yml');
130
        }
131
    }
132
133
    private function includeGoals($paths)
134
    {
135
        foreach ((array) $paths as $path) {
136
            $this->goals = ArrayHelper::merge(
137
                $this->goals,
138
                $this->readYaml($path)
139
            );
140
        }
141
    }
142
143
    private function readYaml($path)
144
    {
145
        return Yaml::parse(FileHelper::read($path));
146
    }
147
148
    /**
149
     * Adds aliases:
150
     * - @root alias to current project root dir
151
     * - @hidev own alias
152
     * - current package namespace for it could be used from hidev
153
     * - aliases listed in config.
154
     */
155
    private function addAliases()
156
    {
157
        Yii::setAlias('@root', $this->getRootDir());
158
        Yii::setAlias('@hidev', dirname(__DIR__));
159
        $package = $this->goals['package'];
160
        $alias  = isset($package['namespace']) ? strtr($package['namespace'], '\\', '/') : '';
161
        if ($alias && !Yii::getAlias('@' . $alias, false)) {
162
            $srcdir = Yii::getAlias('@root/' . ($package['src'] ?: 'src'));
163
            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 162 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...
164
        }
165
        $aliases = $this->goals['aliases'];
166
        if (!empty($aliases) && is_array($aliases)) {
167
            foreach ($aliases as $alias => $path) {
168
                if (!$this->hasAlias($alias)) {
169
                    Yii::setAlias($alias, $path);
170
                }
171
            }
172
        }
173
    }
174
175
    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...
176
    {
177
        $pos = strpos($alias, '/');
178
179
        return $pos === false ? isset(Yii::$aliases[$alias]) : isset(Yii::$aliases[substr($alias, 0, $pos)][$alias]);
180
    }
181
182
    /**
183
     * - install configured plugins and register their app config
184
     * - install project dependencies and register
185
     * - register application config files.
186
     */
187
    private function requireAll()
188
    {
189
        $vendors = [];
190
        $plugins = $this->goals['plugins'];
191
        if ($plugins) {
192
            $file = File::create('.hidev/composer.json');
193
            $data = ArrayHelper::merge($file->load(), ['require' => $plugins]);
194
            if ($file->save($data) || !is_dir('.hidev/vendor')) {
195
                $this->updateDotHidev();
196
            }
197
            $vendors[] = $this->buildRootPath('.hidev/vendor');
198
        }
199
        if ($this->needsComposerInstall()) {
200
            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...
201
                throw new InvalidParamException('Failed initialize project with composer install');
202
            }
203
        }
204
        $vendors[] = $this->buildRootPath('vendor');
205
206
        foreach ($vendors as $vendor) {
207
            foreach (['console', 'hidev'] as $name) {
208
                $path = ConfigPlugin::path($name, $vendor);
209
                if (file_exists($path)) {
210
                    $this->appFiles[] = $path;
211
                }
212
            }
213
        }
214
    }
215
216
    /**
217
     * Update action.
218
     * @return int exit code
219
     */
220
    public function updateDotHidev()
221
    {
222
        if (file_exists('.hidev/composer.json')) {
223
            return $this->passthru('composer', ['update', '-d', '.hidev', '--prefer-source', '--ansi']);
224
        }
225
    }
226
227
    /**
228
     * Passthru command.
229
     * @param string $command
230
     * @param array $args
231
     * @return int exit code
232
     */
233
    private function passthru($command, $args)
234
    {
235
        $binary = new BinaryPhp([
236
            'name' => $command,
237
        ]);
238
239
        return $binary->passthru($args);
240
    }
241
242
    private function needsComposerInstall()
243
    {
244
        if (file_exists('vendor')) {
245
            return false;
246
        }
247
        if (!file_exists('composer.json')) {
248
            return false;
249
        }
250
251
        return true;
252
253
    /*
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...
254
        $data = File::create('composer.json')->load();
255
        foreach (['require', 'require-dev'] as $key) {
256
            if (isset($data[$key])) {
257
                foreach ($data[$key] as $package => $version) {
258
                    list(, $name) = explode('/', $package);
259
                    if (strncmp($name, 'hidev-', 6) === 0) {
260
                        return true;
261
                    }
262
                }
263
            }
264
        }
265
266
        return false;
267
    */
268
    }
269
270
    /**
271
     * Include all configured includes.
272
     */
273
    private function includeAll()
274
    {
275
        $config = $this->readConfig();
276
        $files = array_merge(
277
            (array) $this->goals['include'],
278
            (array) $config['components']['include']
279
        );
280
        $this->includeGoals($files);
281
    }
282
283
    /**
284
     * Registers more application config to load.
285
     */
286
    private function moreConfig()
287
    {
288
        $paths = $this->goals['config'];
289
        foreach ((array) $paths as $path) {
290
            if ($path) {
291
                $this->appFiles[] = $path;
292
            }
293
        }
294
    }
295
296
    public function setRootDir($value)
297
    {
298
        $this->_rootDir = $value;
299
    }
300
301
    public function getRootDir()
302
    {
303
        if ($this->_rootDir === null) {
304
            $this->_rootDir = $this->findRootDir();
305
        }
306
307
        return $this->_rootDir;
308
    }
309
310
    /**
311
     * Chdirs to project's root by looking for config file in the current directory and up.
312
     * @throws InvalidParamException when failed to find
313
     * @return string path to the root directory of hidev project
314
     */
315
    private function findRootDir()
316
    {
317
        $configFile = 'hidev.yml';
318
        for ($i = 0; $i < 9; ++$i) {
319
            if (file_exists($configFile)) {
320
                return getcwd();
321
            }
322
            chdir('..');
323
        }
324
        throw new InvalidParamException("Not a hidev project (or any of the parent directories).\nUse `hidev init` to initialize hidev project.");
325
    }
326
327
    public function buildRootPath($subpath)
328
    {
329
        return $this->getRootDir() . DIRECTORY_SEPARATOR . $subpath;
330
    }
331
}
332