Passed
Branch master (9957c5)
by Jean-Christophe
12:44
created

Startup::injectDependences()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

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