Test Failed
Push — master ( 16eae6...cefc05 )
by Jean-Christophe
12:30
created

Startup::getControllerInstance()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5.3906

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 15
ccs 6
cts 8
cp 0.75
rs 9.6111
cc 5
nc 8
nop 1
crap 5.3906
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
	private static $controllers = [ ];
27 47
28 47
	private static function parseUrl(&$url) {
29 3
		if (! $url) {
30
			$url = "_default";
31 47
		}
32
		return self::$urlParts = \explode ( "/", \rtrim ( $url, '/' ) );
33
	}
34 46
35
	public static function getControllerInstance($controllerName) {
36 46
		if (! isset ( self::$controllers [$controllerName] )) {
37 46
			try {
38 46
				$controller = new $controllerName ();
39 46
				// Dependency injection
40 46
				if (isset ( self::$config ['di'] ) && \is_array ( self::$config ['di'] )) {
41
					self::injectDependences ( $controller );
42
				}
43
				self::$controllers [$controllerName] = $controller;
44
			} catch ( \Exception $e ) {
45 46
				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
		return self::$controllers [$controllerName];
50
	}
51
52 46
	private static function startTemplateEngine(&$config) {
53 46
		try {
54 46
			$templateEngine = $config ['templateEngine'];
55 46
			$engineOptions = $config ['templateEngineOptions'] ?? array ('cache' => false );
56
			$engine = new $templateEngine ( $engineOptions );
57 46
			if ($engine instanceof TemplateEngine) {
58 46
				self::$templateEngine = $engine;
59
			}
60 46
		} catch ( \Exception $e ) {
61 46
			echo $e->getTraceAsString ();
62
		}
63
	}
64
65
	/**
66
	 * Handles the request
67
	 *
68
	 * @param array $config The loaded config array
69
	 */
70 47
	public static function run(array &$config) {
71 47
		self::init ( $config );
72 47
		self::forward ( $_GET ['c'] );
73 19
	}
74 19
75 19
	/**
76
	 * Initialize the app with $config array
77 5
	 *
78
	 * @param array $config
79
	 */
80 5
	public static function init(array &$config) {
81
		self::$config = $config;
82
		if (isset ( $config ['templateEngine'] )) {
83 47
			self::startTemplateEngine ( $config );
84 47
		}
85
		if (isset ( $config ['sessionName'] )) {
86 47
			USession::start ( $config ['sessionName'] );
87
		}
88
	}
89
90
	/**
91
	 * Forwards to url
92
	 *
93 3
	 * @param string $url The url to forward to
94 3
	 * @param boolean $initialize If true, the **initialize** method of the controller is called
95 3
	 * @param boolean $finalize If true, the **finalize** method of the controller is called
96 3
	 */
97 3
	public static function forward($url, $initialize = true, $finalize = true) {
98
		$u = self::parseUrl ( $url );
99
		if (\is_array ( Router::getRoutes () ) && ($ru = Router::getRoute ( $url, true, self::$config ['debug'] ?? false)) !== false) {
100
			if (\is_array ( $ru )) {
101
				if (\is_string ( $ru [0] )) {
102
					self::runAction ( $ru, $initialize, $finalize );
103
				} else {
104
					self::runCallable ( $ru );
105
				}
106
			} else {
107
				echo $ru; // Displays route response from cache
108 48
			}
109 48
		} else {
110 48
			$u [0] = self::setCtrlNS () . $u [0];
111 48
			self::runAction ( $u, $initialize, $finalize );
112 48
		}
113 48
	}
114
115
	/**
116 48
	 * Returns the template engine instance
117
	 *
118 48
	 * @return TemplateEngine
119 48
	 */
120
	public static function getTempateEngineInstance() {
121 48
		$config = self::$config;
122 6
		if (isset ( $config ['templateEngine'] )) {
123
			$templateEngine = $config ['templateEngine'];
124 48
			return new $templateEngine ( [ ] );
125 48
		}
126
	}
127
128 48
	/**
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
		$uSize = \sizeof ( $u );
138
		self::$action = ($uSize > 1) ? $u [1] : 'index';
139 35
		self::$actionParams = ($uSize > 2) ? \array_slice ( $u, 2 ) : [ ];
140 34
141 34
		$controller = self::getControllerInstance ( $ctrl );
142 34
		if (! $controller->isValid ( self::$action )) {
143
			$controller->onInvalidControl ();
144
		} else {
145
			if ($initialize) {
146
				$controller->initialize ();
147 48
			}
148
			try {
149
				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
					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
			if ($finalize) {
160
				$controller->finalize ();
161
			}
162
		}
163
	}
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 51
			self::$actionParams = \array_slice ( $u, 1 );
174 51
		}
175 51
		if (isset ( self::$config ['di'] )) {
176 33
			$di = self::$config ['di'];
177 33
			if (\is_array ( $di )) {
178 33
				self::$actionParams = \array_merge ( self::$actionParams, $di );
179 4
			}
180
		}
181 33
		\call_user_func_array ( $u [0], self::$actionParams );
182
	}
183
184
	/**
185
	 * Injects the dependencies from the **di** config key in a controller
186 51
	 *
187 51
	 * @param Controller $controller The controller
188 48
	 */
189 48
	public static function injectDependences($controller) {
190
		$di = DiManager::fetch ( $controller );
191
		if ($di !== false) {
192 51
			foreach ( $di as $k => $v ) {
193
				$setter = 'set' . ucfirst ( $k );
194
				if (\method_exists ( $controller, $setter )) {
195
					$controller->$setter ( $v ( $controller ) );
196
				} else {
197
					$controller->$k = $v ( $controller );
198
				}
199
			}
200
		}
201
202 1
		$di = self::$config ['di'] ?? [ ];
203 1
		if (isset ( $di ['@exec'] )) {
204 1
			foreach ( $di ['@exec'] as $k => $v ) {
205 1
				$controller->$k = $v ( $controller );
206
			}
207
		}
208
	}
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
	public static function runAsString(array &$u, $initialize = true, $finalize = true) {
219
		\ob_start ();
220
		self::runAction ( $u, $initialize, $finalize );
221
		return \ob_get_clean ();
222 8
	}
223 8
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 2
	}
232 2
233
	/**
234
	 * Returns the active controller name
235
	 *
236
	 * @return string
237
	 */
238
	public static function getController() {
239
		return self::$controller;
240 1
	}
241 1
242
	/**
243
	 * Returns the class simple name of the active controller
244
	 *
245
	 * @return string
246
	 */
247
	public static function getControllerSimpleName() {
248
		return (new \ReflectionClass ( self::$controller ))->getShortName ();
249 21
	}
250 21
251
	/**
252
	 * Returns the extension for view files
253
	 *
254
	 * @return string
255
	 */
256
	public static function getViewNameFileExtension() {
257
		return "html";
258 4
	}
259 4
260
	/**
261
	 * Returns tha active action
262
	 *
263
	 * @return string
264
	 */
265
	public static function getAction() {
266
		return self::$action;
267 48
	}
268 48
269
	/**
270
	 * Returns the active parameters
271
	 *
272
	 * @return array
273
	 */
274
	public static function getActionParams() {
275
		return self::$actionParams;
276 3
	}
277 3
278
	/**
279
	 * Returns the framework directory
280
	 *
281
	 * @return string
282
	 */
283
	public static function getFrameworkDir() {
284
		return \dirname ( __FILE__ );
285 1
	}
286 1
287
	/**
288
	 * Returns the application directory (app directory)
289
	 *
290
	 * @return string
291
	 */
292
	public static function getApplicationDir() {
293
		return \dirname ( \ROOT );
294
	}
295
296
	/**
297
	 * Returns the application name
298
	 *
299
	 * @return string
300
	 */
301
	public static function getApplicationName() {
302
		return \basename ( \dirname ( \ROOT ) );
303
	}
304
}
305