Completed
Push — master ( 770069...1626fc )
by Andrii
05:34
created

Application::readConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
crap 2
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 Exception;
14
use hidev\helpers\ConfigPlugin;
15
use Yii;
16
use yii\base\InvalidParamException;
17
use yii\base\ViewContextInterface;
18
use yii\console\Exception as ConsoleException;
19
use yii\helpers\ArrayHelper;
20
21
/**
22
 * The Application.
23
 */
24
class Application extends \yii\console\Application implements ViewContextInterface
25
{
26
    protected $_viewPath;
27
28
    protected $_config;
29
30
    protected $_first = true;
31
32 5
    public function __construct($config = [])
33
    {
34 5
        $this->_config = $config;
35 5
        parent::__construct($config);
36 5
    }
37
38
    /**
39
     * Creates application with given config and runs it.
40
     * @param array $config
41
     * @return int exit code
42
     */
43
    public static function main(array $config)
44
    {
45
        try {
46
            $app = static::create($config);
47
            $exitCode = $app->run();
48
        } catch (Exception $e) {
49
            /*if ($e instanceof InvalidParamException || $e instanceof ConsoleException) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
50
                Yii::error($e->getMessage());
51
                $exitCode = 1;
52
            } else {
53
                throw $e;
54
            }*/
55
                throw $e;
56
        }
57
58
        return $exitCode;
59
    }
60
61 5
    public static function create(array $config)
62
    {
63 5
        Yii::setLogger(Yii::createObject(\hidev\base\Logger::class));
64
        /*$config = ArrayHelper::merge(
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
65
            static::readVendorConfig($config['vendorPath'], 'hidev'),
66
            $config
67
        );*/
68
69 5
        return new static($config);
70
    }
71
72 2
    public function loadExtraConfig($path)
73
    {
74 2
        $this->setExtraConfig(static::readConfig($path));
75 2
    }
76
77 2
    public static function readConfig($path)
78
    {
79 2
        $path = Yii::getAlias($path);
80
81 2
        return file_exists($path) ? require $path : [];
82
    }
83
84
    /**
85
     * Load extra config files.
86
     * @param string $vendor path to vendor dir
87
     */
88
    public function loadExtraVendor($vendor)
89
    {
90
        $this->setExtraEnv(static::readVendorConfig($vendor, 'dotenv'));
91
        $this->setExtraConfig(static::readVendorConfig($vendor, 'hidev'));
92
    }
93
94
    public function readVendorConfig($vendor, $name)
95
    {
96
        return static::readConfig(ConfigPlugin::path($vendor, $name));
97
    }
98
99
    /**
100
     * Sets extra environment variables.
101
     * @param array $config
0 ignored issues
show
Bug introduced by
There is no parameter named $config. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
102
     */
103
    public function setExtraEnv($vars)
0 ignored issues
show
Coding Style introduced by
setExtraEnv uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
104
    {
105
        foreach ($vars as $key => $value) {
106
            $_ENV[$key] = $value;
107
        }
108
    }
109
110
    /**
111
     * Implements extra configuration.
112
     * @param array $config
113
     */
114 2
    public function setExtraConfig($config)
115
    {
116 2
        $this->_config = $config = ArrayHelper::merge($config, $this->_config);
117 2
        $backup = $this->get('config')->getItems();
118 2
        $this->clear('config');
119
120 2
        foreach (['params', 'aliases', 'modules', 'components'] as $key) {
121 2
            if (isset($config[$key])) {
122 2
                $this->{'setExtra' . ucfirst($key)}($config[$key]);
123 2
            }
124 2
        }
125
126 2
        $this->get('config')->mergeItems($backup);
127 2
    }
128
129
    /**
130
     * Implements extra params.
131
     * @param array $params
132
     */
133 2
    public function setExtraParams($params)
134
    {
135 2
        if (is_array($params) && !empty($params)) {
136
            $this->params = ArrayHelper::merge($this->params, $params);
137
        }
138 2
    }
139
140
    /**
141
     * Implements extra aliases.
142
     * @param array $aliases
143
     */
144
    public function setExtraAliases($aliases)
145
    {
146
        if (is_array($aliases) && !empty($aliases)) {
147
            $this->setAliases($aliases);
148
        }
149
    }
150
151
    /**
152
     * Implements extra modules.
153
     * @param array $modules
154
     */
155
    public function setExtraModules($modules)
156
    {
157
        if (is_array($modules) && !empty($modules)) {
158
            $this->setModules($modules);
159
        }
160
    }
161
162
    /**
163
     * Implements extra components.
164
     * Does NOT touch already instantiated components.
165
     * @param array $components
166
     */
167 2
    public function setExtraComponents($components)
168
    {
169 2
        if (is_array($components) && !empty($components)) {
170 2
            foreach ($components as $id => $component) {
171 2
                if ($this->has($id, true)) {
172 2
                    unset($components[$id]);
173 2
                }
174 2
            }
175 2
            $this->setComponents($components);
176 2
        }
177 2
    }
178
179 5
    public function createControllerByID($id)
180
    {
181
        /// skip start for init goal
182 5
        if ($this->_first) {
183 5
            $this->_first = false;
184 5
            static $skips = ['init' => 1, 'clone' => 1, '--version' => 1];
185 5
            if (!isset($skips[$id])) {
186 2
                $this->runRequest('start');
187 2
            }
188 5
        }
189
190 5
        if ($this->get('config')->hasGoal($id)) {
191 5
            return $this->get('config')->get($id);
192
        }
193
194 4
        $controller = parent::createControllerByID($id);
195 4
        $this->get('config')->set($id, $controller);
196
197 4
        return $controller;
198
    }
199
200
    /**
201
     * Run request.
202
     * @param string|array $query
203
     * @return Response
204
     */
205 5
    public function runRequest($query)
206
    {
207 5
        $request = Yii::createObject([
208 5
            'class'  => 'hidev\base\Request',
209 5
            'params' => is_array($query) ? $query : array_filter(explode(' ', $query)),
210 5
        ]);
211
212 5
        return $this->handleRequest($request);
213
    }
214
}
215