Completed
Push — master ( b19c96...9aea22 )
by Jean-Christophe
01:59
created

Startup::runAction()   C

Complexity

Conditions 7
Paths 24

Size

Total Lines 27
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 22
nc 24
nop 3
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\utils\base\UFileSystem;
9
10
class Startup {
11
	public static $urlParts;
12
	private static $config;
13
	private static $ctrlNS;
14
	private static $controller;
15
	private static $action;
16
	private static $actionParams;
17
18
	public static function run(array &$config, $url) {
19
		self::$config = $config;
20
		self::startTemplateEngine ( $config );
21
		if (isset ( $config ["sessionName"] ))
22
			USession::start ( $config ["sessionName"] );
23
		self::forward ( $url );
24
	}
25
26
	public static function forward($url) {
27
		$u = self::parseUrl ( $url );
28
		if (($ru = Router::getRoute ( $url )) !== false) {
29
			if (\is_array ( $ru ))
30
				self::runAction ( $ru );
31
			else
32
				echo $ru;
33
		} else {
34
			self::setCtrlNS ();
35
			$u [0] = self::$ctrlNS . $u [0];
36
			if (\class_exists ( $u [0] )) {
37
				self::runAction ( $u );
38
			} else {
39
				\header ( 'HTTP/1.0 404 Not Found', true, 404 );
40
				print "The controller `" . $u [0] . "` doesn't exists! <br/>";
41
			}
42
		}
43
	}
44
45
	public static function getNS($part = "controllers") {
46
		$config = self::$config;
47
		$ns = $config ["mvcNS"] [$part];
48
		if ($ns !== "" && $ns !== null) {
49
			$ns .= "\\";
50
		}
51
		return $ns;
52
	}
53
54
	private static function setCtrlNS() {
55
		self::$ctrlNS = self::getNS ();
56
	}
57
58
	private static function parseUrl(&$url) {
59
		if (! $url) {
60
			$url = "_default";
61
		}
62
		if (UString::endswith ( $url, "/" ))
63
			$url = \substr ( $url, 0, strlen ( $url ) - 1 );
64
		self::$urlParts = \explode ( "/", $url );
65
66
		return self::$urlParts;
67
	}
68
69
	private static function startTemplateEngine($config) {
70
		try {
71
			$engineOptions = array ('cache' => ROOT . DS . "views/cache/" );
72
			if (isset ( $config ["templateEngine"] )) {
73
				$templateEngine = $config ["templateEngine"];
74
				if (isset ( $config ["templateEngineOptions"] )) {
75
					$engineOptions = $config ["templateEngineOptions"];
76
				}
77
				$engine = new $templateEngine ( $engineOptions );
78
				if ($engine instanceof TemplateEngine) {
79
					self::$config ["templateEngine"] = $engine;
80
				}
81
			}
82
		} catch ( \Exception $e ) {
83
			echo $e->getTraceAsString ();
84
		}
85
	}
86
87
	public static function runAction($u, $initialize = true, $finalize = true) {
88
		$config = self::getConfig ();
89
		$ctrl = $u [0];
90
		self::$controller = $ctrl;
91
		self::$action = "index";
92
		if (\sizeof ( $u ) > 1)
93
			self::$action = $u [1];
94
		if (\sizeof ( $u ) > 2)
95
			self::$actionParams=array_slice ( $u, 2 );
96
97
		$controller = new $ctrl ();
98
		if (! $controller instanceof Controller) {
99
			print "`{$u[0]}` isn't a controller instance.`<br/>";
100
			return;
101
		}
102
		// Dependency injection
103
		self::injectDependences($controller, $config);
104
		if(!$controller->isValid(self::$action)){
105
			$controller->onInvalidControl();
106
		}else{
107
			if ($initialize)
108
				$controller->initialize ();
109
			self::callController ( $controller, $u );
110
			if ($finalize)
111
				$controller->finalize ();
112
		}
113
	}
114
	
115
	public static function injectDependences($controller,$config){
116
		if (\array_key_exists ( "di", $config )) {
117
			$di = $config ["di"];
118
			if (\is_array ( $di )) {
119
				foreach ( $di as $k => $v ) {
120
					$controller->$k = $v ( $controller );
121
				}
122
			}
123
		}
124
	}
125
126
	public static function runAsString($u, $initialize = true, $finalize = true) {
127
		\ob_start ();
128
		self::runAction ( $u, $initialize, $finalize );
129
		return \ob_get_clean ();
130
	}
131
132
	private static function callController(Controller $controller, $u) {
133
		$urlSize = sizeof ( $u );
134
		switch ($urlSize) {
135
			case 1 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
136
				$controller->index ();
137
				break;
138
			case 2 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
139
				$action = $u [1];
140
				// Appel de la méthode (2ème élément du tableau)
141
				if (\method_exists ( $controller, $action )) {
142
					$controller->$action ();
143
				} else {
144
					print "The method `{$action}` doesn't exists on controller `" . $u [0] . "`<br/>";
145
				}
146
				break;
147
			default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
148
				// Appel de la méthode en lui passant en paramètre le reste du tableau
149
				\call_user_func_array ( array ($controller,$u [1] ), self::$actionParams );
150
				break;
151
		}
152
	}
153
154
	public static function getConfig() {
155
		return self::$config;
156
	}
157
158
	public static function setConfig($config) {
159
		self::$config = $config;
160
	}
161
162
	private static function needsKeyInConfigArray(&$result, $array, $needs) {
163
		foreach ( $needs as $need ) {
164
			if (! isset ( $array [$need] ) || UString::isNull ( $array [$need] )) {
165
				$result [] = $need;
166
			}
167
		}
168
	}
169
170
	public static function checkDbConfig() {
171
		$config = self::$config;
172
		$result = [ ];
173
		$needs = [ "type","dbName","serverName" ];
174
		if (! isset ( $config ["database"] )) {
175
			$result [] = "database";
176
		} else {
177
			self::needsKeyInConfigArray ( $result, $config ["database"], $needs );
178
		}
179
		return $result;
180
	}
181
182
	public static function checkModelsConfig() {
183
		$config = self::$config;
184
		$result = [ ];
185
		if (! isset ( $config ["mvcNS"] )) {
186
			$result [] = "mvcNS";
187
		} else {
188
			self::needsKeyInConfigArray ( $result, $config ["mvcNS"], [ "models" ] );
189
		}
190
		return $result;
191
	}
192
193
	public static function getModelsDir() {
194
		return self::$config ["mvcNS"] ["models"];
195
	}
196
197
	public static function getModelsCompletePath() {
198
		return ROOT . DS . self::getModelsDir ();
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
	public static function getController() {
211
		return self::$controller;
212
	}
213
	
214
	public static function getControllerSimpleName() {
215
		return (new \ReflectionClass(self::$controller))->getShortName();
216
	}
217
	
218
	public static function getViewNameFileExtension(){
219
		return "html";
220
	}
221
222
	public static function getAction() {
223
		return self::$action;
224
	}
225
	
226
	public static function getActionParams() {
227
		return self::$actionParams;
228
	}
229
230
	public static function getFrameworkDir() {
231
		return \dirname ( __FILE__ );
232
	}
233
234
	public static function getApplicationDir() {
235
		return \dirname ( ROOT );
236
	}
237
	
238
	public static function getApplicationName() {
239
		return basename(\dirname ( ROOT ));
240
	}
241
	
242
	public static function reloadConfig(){
243
		$appDir=\dirname ( ROOT );
244
		$filename=$appDir."/app/config/config.php";
245
		self::$config=include($filename);
246
		self::startTemplateEngine(self::$config);
247
		return self::$config;
248
	}
249
	
250
	public static function saveConfig($content){
251
		$appDir=\dirname ( ROOT );
252
		$filename=$appDir."/app/config/config.php";
253
		$oldFilename=$appDir."/app/config/config.old.php";
254
		if (!file_exists($filename) || copy($filename, $oldFilename)) {
255
			return UFileSystem::save($filename,$content);
256
		}
257
		return false;
258
	}
259
}
260