Completed
Push — master ( 495f03...3ba762 )
by Jean-Christophe
01:52
created

Startup::needsKeyInConfigArray()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.2
c 0
b 0
f 0
cc 4
eloc 4
nc 3
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
17
	public static function run(array &$config, $url) {
18
		self::$config = $config;
19
		self::startTemplateEngine ( $config );
20
		if (isset ( $config ["sessionName"] ))
21
			USession::start ( $config ["sessionName"] );
22
		self::forward ( $url );
23
	}
24
25
	public static function forward($url) {
26
		$u = self::parseUrl ( $url );
27
		if (($ru = Router::getRoute ( $url )) !== false) {
28
			if (\is_array ( $ru ))
29
				self::runAction ( $ru );
30
			else
31
				echo $ru;
32
		} else {
33
			self::setCtrlNS ();
34
			$u [0] = self::$ctrlNS . $u [0];
35
			if (\class_exists ( $u [0] )) {
36
				self::runAction ( $u );
37
			} else {
38
				\header ( 'HTTP/1.0 404 Not Found', true, 404 );
39
				print "The controller `" . $u [0] . "` doesn't exists! <br/>";
40
			}
41
		}
42
	}
43
44
	public static function getNS($part = "controllers") {
45
		$config = self::$config;
46
		$ns = $config ["mvcNS"] [$part];
47
		if ($ns !== "" && $ns !== null) {
48
			$ns .= "\\";
49
		}
50
		return $ns;
51
	}
52
53
	private static function setCtrlNS() {
54
		self::$ctrlNS = self::getNS ();
55
	}
56
57
	private static function parseUrl(&$url) {
58
		if (! $url) {
59
			$url = "_default";
60
		}
61
		if (UString::endswith ( $url, "/" ))
62
			$url = \substr ( $url, 0, strlen ( $url ) - 1 );
63
		self::$urlParts = \explode ( "/", $url );
64
65
		return self::$urlParts;
66
	}
67
68
	private static function startTemplateEngine($config) {
69
		try {
70
			$engineOptions = array ('cache' => ROOT . DS . "views/cache/" );
71
			if (isset ( $config ["templateEngine"] )) {
72
				$templateEngine = $config ["templateEngine"];
73
				if (isset ( $config ["templateEngineOptions"] )) {
74
					$engineOptions = $config ["templateEngineOptions"];
75
				}
76
				$engine = new $templateEngine ( $engineOptions );
77
				if ($engine instanceof TemplateEngine) {
78
					self::$config ["templateEngine"] = $engine;
79
				}
80
			}
81
		} catch ( \Exception $e ) {
82
			echo $e->getTraceAsString ();
83
		}
84
	}
85
86
	public static function runAction($u, $initialize = true, $finalize = true) {
87
		$config = self::getConfig ();
88
		$ctrl = $u [0];
89
		self::$controller = $ctrl;
90
		self::$action = "index";
91
		if (\sizeof ( $u ) > 1)
92
			self::$action = $u [1];
93
94
		$controller = new $ctrl ();
95
		if (! $controller instanceof Controller) {
96
			print "`{$u[0]}` isn't a controller instance.`<br/>";
97
			return;
98
		}
99
		// Dependency injection
100
		self::injectDependences($controller, $config);
101
102
		if ($initialize)
103
			$controller->initialize ();
104
		self::callController ( $controller, $u );
105
		if ($finalize)
106
			$controller->finalize ();
107
	}
108
	
109
	public static function injectDependences($controller,$config){
110
		if (\array_key_exists ( "di", $config )) {
111
			$di = $config ["di"];
112
			if (\is_array ( $di )) {
113
				foreach ( $di as $k => $v ) {
114
					$controller->$k = $v ( $controller );
115
				}
116
			}
117
		}
118
	}
119
120
	public static function runAsString($u, $initialize = true, $finalize = true) {
121
		\ob_start ();
122
		self::runAction ( $u, $initialize, $finalize );
123
		return \ob_get_clean ();
124
	}
125
126
	private static function callController(Controller $controller, $u) {
127
		$urlSize = sizeof ( $u );
128
		switch ($urlSize) {
129
			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...
130
				$controller->index ();
131
				break;
132
			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...
133
				$action = $u [1];
134
				// Appel de la méthode (2ème élément du tableau)
135
				if (\method_exists ( $controller, $action )) {
136
					$controller->$action ();
137
				} else {
138
					print "The method `{$action}` doesn't exists on controller `" . $u [0] . "`<br/>";
139
				}
140
				break;
141
			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...
142
				// Appel de la méthode en lui passant en paramètre le reste du tableau
143
				\call_user_func_array ( array ($controller,$u [1] ), array_slice ( $u, 2 ) );
144
				break;
145
		}
146
	}
147
148
	public static function getConfig() {
149
		return self::$config;
150
	}
151
152
	public static function setConfig($config) {
153
		self::$config = $config;
154
	}
155
156
	private static function needsKeyInConfigArray(&$result, $array, $needs) {
157
		foreach ( $needs as $need ) {
158
			if (! isset ( $array [$need] ) || UString::isNull ( $array [$need] )) {
159
				$result [] = $need;
160
			}
161
		}
162
	}
163
164
	public static function checkDbConfig() {
165
		$config = self::$config;
166
		$result = [ ];
167
		$needs = [ "type","dbName","serverName" ];
168
		if (! isset ( $config ["database"] )) {
169
			$result [] = "database";
170
		} else {
171
			self::needsKeyInConfigArray ( $result, $config ["database"], $needs );
172
		}
173
		return $result;
174
	}
175
176
	public static function checkModelsConfig() {
177
		$config = self::$config;
178
		$result = [ ];
179
		if (! isset ( $config ["mvcNS"] )) {
180
			$result [] = "mvcNS";
181
		} else {
182
			self::needsKeyInConfigArray ( $result, $config ["mvcNS"], [ "models" ] );
183
		}
184
		return $result;
185
	}
186
187
	public static function getModelsDir() {
188
		return self::$config ["mvcNS"] ["models"];
189
	}
190
191
	public static function getModelsCompletePath() {
192
		return ROOT . DS . self::getModelsDir ();
193
	}
194
195
	public static function errorHandler($message = "", $code = 0, $severity = 1, $filename = null, int $lineno = 0, $previous = NULL) {
196
		if (\error_reporting () == 0) {
197
			return;
198
		}
199
		if (\error_reporting () & $severity) {
200
			throw new \ErrorException ( $message, 0, $severity, $filename, $lineno, $previous );
201
		}
202
	}
203
204
	public static function getController() {
205
		return self::$controller;
206
	}
207
	
208
	public static function getControllerSimpleName() {
209
		return (new \ReflectionClass(self::$controller))->getShortName();
210
	}
211
	
212
	public static function getViewNameFileExtension(){
213
		return "html";
214
	}
215
216
	public static function getAction() {
217
		return self::$action;
218
	}
219
220
	public static function getFrameworkDir() {
221
		return \dirname ( __FILE__ );
222
	}
223
224
	public static function getApplicationDir() {
225
		return \dirname ( ROOT );
226
	}
227
	
228
	public static function getApplicationName() {
229
		return basename(\dirname ( ROOT ));
230
	}
231
	
232
	public static function reloadConfig(){
233
		$appDir=\dirname ( ROOT );
234
		$filename=$appDir."/app/config/config.php";
235
		self::$config=include($filename);
236
		self::startTemplateEngine(self::$config);
237
		return self::$config;
238
	}
239
	
240
	public static function saveConfig($content){
241
		$appDir=\dirname ( ROOT );
242
		$filename=$appDir."/app/config/config.php";
243
		$oldFilename=$appDir."/app/config/config.old.php";
244
		if (!file_exists($filename) || copy($filename, $oldFilename)) {
245
			return UFileSystem::save($filename,$content);
246
		}
247
		return false;
248
	}
249
}
250