Test Failed
Push — master ( b1fea5...97448e )
by Jean-Christophe
13:28
created

Startup::runAction()   D

Complexity

Conditions 12
Paths 336

Size

Total Lines 37
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 12.3654

Importance

Changes 0
Metric Value
eloc 28
c 0
b 0
f 0
dl 0
loc 37
ccs 19
cts 22
cp 0.8636
rs 4.4333
cc 12
nc 336
nop 3
crap 12.3654

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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