Passed
Push — master ( 9e15fe...1d956f )
by Jean-Christophe
09:32
created

Startup   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 284
Duplicated Lines 0 %

Test Coverage

Coverage 78.33%

Importance

Changes 7
Bugs 0 Features 1
Metric Value
wmc 52
eloc 107
c 7
b 0
f 1
dl 0
loc 284
ccs 94
cts 120
cp 0.7833
rs 7.44

20 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 3 1
A getTempateEngineInstance() 0 5 2
A getApplicationName() 0 2 1
A getControllerSimpleName() 0 2 1
A errorHandler() 0 6 3
A getFrameworkDir() 0 2 1
A parseUrl() 0 5 2
A getController() 0 2 1
A runAsString() 0 4 1
A startTemplateEngine() 0 10 3
B runAction() 0 26 9
A getViewNameFileExtension() 0 2 1
A getAction() 0 2 1
A runCallable() 0 12 4
A init() 0 7 3
A forward() 0 15 5
A getApplicationDir() 0 2 1
A getControllerInstance() 0 15 5
A getActionParams() 0 2 1
A injectDependences() 0 17 6

How to fix   Complexity   

Complex Class

Complex classes like Startup 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.

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 Startup, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Ubiquity\controllers;
4
5
use Ubiquity\controllers\di\DiManager;
6
use Ubiquity\controllers\traits\StartupConfigTrait;
7
use Ubiquity\log\Logger;
8
use Ubiquity\utils\http\USession;
9
use Ubiquity\views\engine\TemplateEngine;
10
11
/**
12
 * Starts the framework.
13
 * This class is part of Ubiquity
14
 *
15
 * @author jcheron <[email protected]>
16
 * @version 1.1.5
17
 *
18
 */
19
class Startup {
20
	use StartupConfigTrait;
21
	public static $urlParts;
22
	public static $templateEngine;
23
	private static $controller;
24
	private static $action;
25
	private static $actionParams;
26
	private static $controllers = [ ];
27
28 47
	private static function parseUrl(&$url) {
29 47
		if (! $url) {
30 3
			$url = "_default";
31
		}
32 47
		return self::$urlParts = \explode ( "/", \rtrim ( $url, '/' ) );
33
	}
34
35 48
	public static function getControllerInstance($controllerName) {
36 48
		if (! isset ( self::$controllers [$controllerName] )) {
37
			try {
38 41
				$controller = new $controllerName ();
39
				// Dependency injection
40 41
				if (isset ( self::$config ['di'] ) && \is_array ( self::$config ['di'] )) {
41 41
					self::injectDependences ( $controller );
42
				}
43 41
				self::$controllers [$controllerName] = $controller;
44 34
			} catch ( \Exception $e ) {
45
				Logger::warn ( 'Startup', 'The controller `' . $controllerName . '` doesn\'t exists! <br/>', 'runAction' );
46
				self::getHttpInstance ()->header ( 'HTTP/1.0 404 Not Found', '', true, 404 );
47
			}
48
		}
49 48
		return self::$controllers [$controllerName];
50
	}
51
52 46
	private static function startTemplateEngine(&$config) {
53
		try {
54 46
			$templateEngine = $config ['templateEngine'];
55 46
			$engineOptions = $config ['templateEngineOptions'] ?? array ('cache' => false );
56 46
			$engine = new $templateEngine ( $engineOptions );
57 46
			if ($engine instanceof TemplateEngine) {
58 46
				self::$templateEngine = $engine;
59
			}
60
		} catch ( \Exception $e ) {
61
			echo $e->getTraceAsString ();
62
		}
63 46
	}
64
65
	/**
66
	 * Handles the request
67
	 *
68
	 * @param array $config The loaded config array
69
	 */
70 46
	public static function run(array &$config) {
71 46
		self::init ( $config );
72 46
		self::forward ( $_GET ['c'] );
73 46
	}
74
75
	/**
76
	 * Initialize the app with $config array
77
	 *
78
	 * @param array $config
79
	 */
80 46
	public static function init(array &$config) {
81 46
		self::$config = $config;
82 46
		if (isset ( $config ['templateEngine'] )) {
83 46
			self::startTemplateEngine ( $config );
84
		}
85 46
		if (isset ( $config ['sessionName'] )) {
86 46
			USession::start ( $config ['sessionName'] );
87
		}
88 46
	}
89
90
	/**
91
	 * Forwards to url
92
	 *
93
	 * @param string $url The url to forward to
94
	 * @param boolean $initialize If true, the **initialize** method of the controller is called
95
	 * @param boolean $finalize If true, the **finalize** method of the controller is called
96
	 */
97 47
	public static function forward($url, $initialize = true, $finalize = true) {
98 47
		$u = self::parseUrl ( $url );
99 47
		if (\is_array ( Router::getRoutes () ) && ($ru = Router::getRoute ( $url, true, self::$config ['debug'] ?? false)) !== false) {
100 19
			if (\is_array ( $ru )) {
101 19
				if (\is_string ( $ru [0] )) {
102 19
					self::runAction ( $ru, $initialize, $finalize );
103
				} else {
104 5
					self::runCallable ( $ru );
105
				}
106
			} else {
107 5
				echo $ru; // Displays route response from cache
108
			}
109
		} else {
110 46
			$u [0] = self::setCtrlNS () . $u [0];
111 46
			self::runAction ( $u, $initialize, $finalize );
112
		}
113 47
	}
114
115
	/**
116
	 * Returns the template engine instance
117
	 *
118
	 * @return TemplateEngine
119
	 */
120 3
	public static function getTempateEngineInstance() {
121 3
		$config = self::$config;
122 3
		if (isset ( $config ['templateEngine'] )) {
123 3
			$templateEngine = $config ['templateEngine'];
124 3
			return new $templateEngine ( [ ] );
125
		}
126
	}
127
128
	/**
129
	 * Runs an action on a controller
130
	 *
131
	 * @param array $u An array containing controller, action and parameters
132
	 * @param boolean $initialize If true, the **initialize** method of the controller is called
133
	 * @param boolean $finalize If true, the **finalize** method of the controller is called
134
	 */
135 48
	public static function runAction(array &$u, $initialize = true, $finalize = true) {
136 48
		self::$controller = $ctrl = $u [0];
137 48
		$uSize = \sizeof ( $u );
138 48
		self::$action = ($uSize > 1) ? $u [1] : 'index';
139 48
		self::$actionParams = ($uSize > 2) ? \array_slice ( $u, 2 ) : [ ];
140
141 48
		$controller = self::getControllerInstance ( $ctrl );
142 48
		if (! $controller->isValid ( self::$action )) {
143 6
			$controller->onInvalidControl ();
144
		} else {
145 48
			if ($initialize) {
146 48
				$controller->initialize ();
147
			}
148
			try {
149 48
				if (\call_user_func_array ( [ $controller,self::$action ], self::$actionParams ) === false) {
150
					Logger::warn ( 'Startup', "The action " . self::$action . " does not exists on controller `{$ctrl}`", 'runAction' );
151 14
					self::getHttpInstance ()->header ( 'HTTP/1.0 404 Not Found', '', true, 404 );
152
				}
153
			} catch ( \Error $e ) {
154
				Logger::warn ( "Startup", $e->getTraceAsString (), "runAction" );
155
				if (self::$config ['debug']) {
156
					throw $e;
157
				}
158
			}
159 48
			if ($finalize) {
160 48
				$controller->finalize ();
161
			}
162
		}
163 48
	}
164
165
	/**
166
	 * Runs a callback
167
	 *
168
	 * @param array $u An array containing a callback, and some parameters
169
	 */
170
	public static function runCallable(array &$u) {
171
		self::$actionParams = [ ];
172
		if (\sizeof ( $u ) > 1) {
173
			self::$actionParams = \array_slice ( $u, 1 );
174
		}
175
		if (isset ( self::$config ['di'] )) {
176
			$di = self::$config ['di'];
177
			if (\is_array ( $di )) {
178
				self::$actionParams = \array_merge ( self::$actionParams, $di );
179
			}
180
		}
181
		\call_user_func_array ( $u [0], self::$actionParams );
182
	}
183
184
	/**
185
	 * Injects the dependencies from the **di** config key in a controller
186
	 *
187
	 * @param Controller $controller The controller
188
	 */
189 44
	public static function injectDependences($controller) {
190 44
		$di = DiManager::fetch ( $controller );
191 44
		if ($di !== false) {
192 33
			foreach ( $di as $k => $v ) {
193 33
				$setter = 'set' . ucfirst ( $k );
194 33
				if (\method_exists ( $controller, $setter )) {
195 4
					$controller->$setter ( $v ( $controller ) );
196
				} else {
197 33
					$controller->$k = $v ( $controller );
198
				}
199
			}
200
		}
201
202 44
		$di = self::$config ['di'] ?? [ ];
203 44
		if (isset ( $di ['@exec'] )) {
204 41
			foreach ( $di ['@exec'] as $k => $v ) {
205 41
				$controller->$k = $v ( $controller );
206
			}
207
		}
208 44
	}
209
210
	/**
211
	 * Runs an action on a controller and returns a string
212
	 *
213
	 * @param array $u
214
	 * @param boolean $initialize If true, the **initialize** method of the controller is called
215
	 * @param boolean $finalize If true, the **finalize** method of the controller is called
216
	 * @return string
217
	 */
218 1
	public static function runAsString(array &$u, $initialize = true, $finalize = true) {
219 1
		\ob_start ();
220 1
		self::runAction ( $u, $initialize, $finalize );
221 1
		return \ob_get_clean ();
222
	}
223
224
	public static function errorHandler($message = "", $code = 0, $severity = 1, $filename = null, int $lineno = 0, $previous = NULL) {
225
		if (\error_reporting () == 0) {
226
			return;
227
		}
228
		if (\error_reporting () & $severity) {
229
			throw new \ErrorException ( $message, 0, $severity, $filename, $lineno, $previous );
230
		}
231
	}
232
233
	/**
234
	 * Returns the active controller name
235
	 *
236
	 * @return string
237
	 */
238 8
	public static function getController() {
239 8
		return self::$controller;
240
	}
241
242
	/**
243
	 * Returns the class simple name of the active controller
244
	 *
245
	 * @return string
246
	 */
247 2
	public static function getControllerSimpleName() {
248 2
		return (new \ReflectionClass ( self::$controller ))->getShortName ();
249
	}
250
251
	/**
252
	 * Returns the extension for view files
253
	 *
254
	 * @return string
255
	 */
256 1
	public static function getViewNameFileExtension() {
257 1
		return "html";
258
	}
259
260
	/**
261
	 * Returns tha active action
262
	 *
263
	 * @return string
264
	 */
265 21
	public static function getAction() {
266 21
		return self::$action;
267
	}
268
269
	/**
270
	 * Returns the active parameters
271
	 *
272
	 * @return array
273
	 */
274 4
	public static function getActionParams() {
275 4
		return self::$actionParams;
276
	}
277
278
	/**
279
	 * Returns the framework directory
280
	 *
281
	 * @return string
282
	 */
283 48
	public static function getFrameworkDir() {
284 48
		return \dirname ( __FILE__ );
285
	}
286
287
	/**
288
	 * Returns the application directory (app directory)
289
	 *
290
	 * @return string
291
	 */
292 3
	public static function getApplicationDir() {
293 3
		return \dirname ( \ROOT );
294
	}
295
296
	/**
297
	 * Returns the application name
298
	 *
299
	 * @return string
300
	 */
301 1
	public static function getApplicationName() {
302 1
		return \basename ( \dirname ( \ROOT ) );
303
	}
304
}
305