Passed
Pull Request — master (#197)
by
unknown
27:39
created

Startup::getControllerSimpleName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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