Completed
Push — master ( 2a3256...770069 )
by Andrii
04:50
created

Application::setExtraParams()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 3
nc 2
nop 1
crap 12
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 Yii;
15
use yii\base\InvalidParamException;
16
use yii\base\ViewContextInterface;
17
use yii\console\Exception as ConsoleException;
18
use yii\helpers\ArrayHelper;
19
20
/**
21
 * The Application.
22
 */
23
class Application extends \yii\console\Application implements ViewContextInterface
24
{
25
    protected $_viewPath;
26
27
    protected $_config;
28
29
    protected $_first = true;
30
31 3
    public function __construct($config = [])
32
    {
33 3
        $this->_config = $config;
34 3
        parent::__construct($config);
35 3
    }
36
37
    /**
38
     * Creates application with given config and runs it.
39
     * @param array $config
40
     * @return int exit code
41
     */
42
    public static function main(array $config)
43
    {
44
        try {
45
            $app = static::create($config);
46
            $exitCode = $app->run();
47
        } catch (Exception $e) {
48
            /*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...
49
                Yii::error($e->getMessage());
50
                $exitCode = 1;
51
            } else {
52
                throw $e;
53
            }*/
54
                throw $e;
55
        }
56
57
        return $exitCode;
58
    }
59
60 3
    public static function create(array $config)
61
    {
62 3
        Yii::setLogger(Yii::createObject('hidev\base\Logger'));
63 3
        $config = ArrayHelper::merge(
64 3
            static::readVendorConfig($config['vendorPath'], 'hidev'),
65
            $config
66
        );
67
68 3
        return new static($config);
69
    }
70
71 3
    public static function readVendorConfig($vendor, $name)
72
    {
73 3
        $path = Yii::getAlias(static::buildConfigPath($vendor, $name));
74
75 3
        return file_exists($path) ? require $path : [];
76
    }
77
78 3
    public static function buildConfigPath($vendor, $name)
79
    {
80
        /// doesn't work when dependencies are not installed
81
        /// return \hiqdev\composer\config\Builder::path($name, $vendor);
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
82 3
        return "$vendor/hiqdev/composer-config-plugin-output/$name.php";
83
    }
84
85
    public function loadExtraConfig($path)
86
    {
87
        $this->setExtraConfig(static::readExtraConfig($path));
0 ignored issues
show
Bug introduced by
The method readExtraConfig() does not seem to exist on object<hidev\base\Application>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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