Passed
Push — master ( 9cc803...84b166 )
by Jean-Christophe
05:35
created

Startup::runAction()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 25
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7.0422

Importance

Changes 0
Metric Value
cc 7
eloc 21
nc 24
nop 3
dl 0
loc 25
ccs 19
cts 21
cp 0.9048
crap 7.0422
rs 8.6506
c 0
b 0
f 0
1
<?php
2
3
namespace Ubiquity\controllers;
4
5
use Ubiquity\utils\base\UString;
6
use Ubiquity\views\engine\TemplateEngine;
7
use Ubiquity\utils\http\USession;
8
use Ubiquity\log\Logger;
9
use Ubiquity\controllers\traits\StartupConfigTrait;
10
11
/**
12
 * Starts the framework
13
 * This class is part of Ubiquity
14
 *
15
 * @author jcheron <[email protected]>
16
 * @version 1.0.0
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 25
	public static function run(array &$config) {
28 25
		self::$config = $config;
29 25
		self::startTemplateEngine ( $config );
30 25
		if (isset ( $config ['sessionName'] ))
31 25
			USession::start ( $config ['sessionName'] );
32 25
		self::forward ( $_GET ['c'] );
33 25
	}
34
35 26
	public static function forward($url, $initialize = true, $finalize = true) {
36 26
		$u = self::parseUrl ( $url );
37 26
		if (($ru = Router::getRoute ( $url )) !== false) {
38 7
			if (\is_array ( $ru )) {
39 7
				if (is_callable ( $ru [0] )) {
40
					self::runCallable ( $ru );
41
				} else {
42 7
					self::_preRunAction ( $ru, $initialize, $finalize );
43
				}
44
			} else {
45 5
				echo $ru; // Displays route response from cache
46
			}
47
		} else {
48 25
			self::setCtrlNS ();
49 25
			$u [0] = self::$ctrlNS . $u [0];
50 25
			self::_preRunAction ( $u, $initialize, $finalize );
51
		}
52 26
	}
53
54 26
	private static function _preRunAction(&$u, $initialize = true, $finalize = true) {
55 26
		if (\class_exists ( $u [0] )) {
56 26
			self::runAction ( $u, $initialize, $finalize );
57
		} else {
58
			\header ( 'HTTP/1.0 404 Not Found', true, 404 );
59
			Logger::warn ( "Startup", "The controller `" . $u [0] . "` doesn't exists! <br/>", "forward" );
60
		}
61 26
	}
62
63 26
	private static function parseUrl(&$url) {
64 26
		if (! $url) {
65 2
			$url = "_default";
66
		}
67 26
		if (UString::endswith ( $url, "/" ))
68 5
			$url = \substr ( $url, 0, strlen ( $url ) - 1 );
69 26
		self::$urlParts = \explode ( "/", $url );
70
71 26
		return self::$urlParts;
72
	}
73
74 25
	private static function startTemplateEngine(&$config) {
75
		try {
76 25
			if (isset ( $config ['templateEngine'] )) {
77 25
				$templateEngine = $config ['templateEngine'];
78 25
				$engineOptions = $config ['templateEngineOptions'] ?? array ('cache' => \ROOT . \DS . 'views/cache/' );
79 25
				$engine = new $templateEngine ( $engineOptions );
80 25
				if ($engine instanceof TemplateEngine) {
81 25
					self::$templateEngine = $engine;
82
				}
83
			}
84
		} catch ( \Exception $e ) {
85
			echo $e->getTraceAsString ();
86
		}
87 25
	}
88
89
	/**
90
	 *
91
	 * @return TemplateEngine
92
	 */
93 2
	public static function getTempateEngineInstance() {
94 2
		$config = self::$config;
95 2
		if (isset ( $config ['templateEngine'] )) {
96 2
			$templateEngine = $config ['templateEngine'];
97 2
			return new $templateEngine ( [ ] );
98
		}
99
	}
100
101 27
	public static function runAction(array &$u, $initialize = true, $finalize = true) {
102 27
		$ctrl = $u [0];
103 27
		self::$controller = $ctrl;
104 27
		self::$action = "index";
105 27
		self::$actionParams = [ ];
106 27
		if (\sizeof ( $u ) > 1)
107 26
			self::$action = $u [1];
108 27
		if (\sizeof ( $u ) > 2)
109 11
			self::$actionParams = array_slice ( $u, 2 );
110
111 27
		$controller = new $ctrl ();
112 27
		if (! $controller instanceof Controller) {
113
			print "`{$u[0]}` isn't a controller instance.`<br/>";
114
			return;
115
		}
116
		// Dependency injection
117 27
		self::injectDependences ( $controller );
118 27
		if (! $controller->isValid ( self::$action )) {
119 6
			$controller->onInvalidControl ();
120
		} else {
121 27
			if ($initialize)
122 27
				$controller->initialize ();
123 27
			self::callController ( $controller, $u );
124 27
			if ($finalize)
125 27
				$controller->finalize ();
126
		}
127 27
	}
128
129
	public static function runCallable(array &$u) {
130
		self::$actionParams = [ ];
131
		if (\sizeof ( $u ) > 1) {
132
			self::$actionParams = array_slice ( $u, 1 );
133
		}
134
		if (isset ( self::$config ['di'] )) {
135
			$di = self::$config ['di'];
136
			if (\is_array ( $di )) {
137
				self::$actionParams = array_merge ( self::$actionParams, $di );
138
			}
139
		}
140
		call_user_func_array ( $u [0], self::$actionParams );
141
	}
142
143 30
	public static function injectDependences($controller) {
144 30
		if (isset ( self::$config ['di'] )) {
145 30
			$di = self::$config ['di'];
146 30
			if (\is_array ( $di )) {
147 30
				foreach ( $di as $k => $v ) {
148 30
					$controller->$k = $v ( $controller );
149
				}
150
			}
151
		}
152 30
	}
153
154 1
	public static function runAsString(array &$u, $initialize = true, $finalize = true) {
155 1
		\ob_start ();
156 1
		self::runAction ( $u, $initialize, $finalize );
157 1
		return \ob_get_clean ();
158
	}
159
160 27
	private static function callController(Controller $controller, array &$u) {
161 27
		$urlSize = sizeof ( $u );
162
		switch ($urlSize) {
163 27
			case 1 :
164 15
				$controller->index ();
165 15
				break;
166 24
			case 2 :
167 20
				$action = $u [1];
168
				// Appel de la méthode (2ème élément du tableau)
169 20
				if (\method_exists ( $controller, $action )) {
170 20
					$controller->$action ();
171
				} else {
172
					Logger::warn ( "Startup", "The method `{$action}` doesn't exists on controller `" . $u [0] . "`", "callController" );
173
				}
174 20
				break;
175
			default :
176
				// Appel de la méthode en lui passant en paramètre le reste du tableau
177 11
				\call_user_func_array ( array ($controller,$u [1] ), self::$actionParams );
178 11
				break;
179
		}
180 27
	}
181
182
	public static function errorHandler($message = "", $code = 0, $severity = 1, $filename = null, int $lineno = 0, $previous = NULL) {
183
		if (\error_reporting () == 0) {
184
			return;
185
		}
186
		if (\error_reporting () & $severity) {
187
			throw new \ErrorException ( $message, 0, $severity, $filename, $lineno, $previous );
188
		}
189
	}
190
191 8
	public static function getController() {
192 8
		return self::$controller;
193
	}
194
195 1
	public static function getControllerSimpleName() {
196 1
		return (new \ReflectionClass ( self::$controller ))->getShortName ();
197
	}
198
199 1
	public static function getViewNameFileExtension() {
200 1
		return "html";
201
	}
202
203 9
	public static function getAction() {
204 9
		return self::$action;
205
	}
206
207 6
	public static function getActionParams() {
208 6
		return self::$actionParams;
209
	}
210
211 28
	public static function getFrameworkDir() {
212 28
		return \dirname ( __FILE__ );
213
	}
214
215 3
	public static function getApplicationDir() {
216 3
		return \dirname ( \ROOT );
217
	}
218
219 1
	public static function getApplicationName() {
220 1
		return basename ( \dirname ( \ROOT ) );
221
	}
222
}
223