Passed
Push — master ( b9a8c8...31c054 )
by Jean-Christophe
12:35
created

Startup::getTempateEngineInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

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