Test Failed
Push — master ( e17a5b...c3015e )
by Jean-Christophe
10:37
created

Startup::_preRunAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.2559

Importance

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