Completed
Push — master ( 0db593...5f0535 )
by Jean-Christophe
01:58
created

Startup::getControllerSimpleName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 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\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 "Le contrôleur `" . $u [0] . "` n'existe pas <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]}` n'est pas une instance de contrôleur.`<br/>";
97
			return;
98
		}
99
		// Dependency injection
100
		if (\array_key_exists ( "di", $config )) {
101
			$di = $config ["di"];
102
			if (\is_array ( $di )) {
103
				foreach ( $di as $k => $v ) {
104
					$controller->$k = $v ( $controller );
105
				}
106
			}
107
		}
108
109
		if ($initialize)
110
			$controller->initialize ();
111
		self::callController ( $controller, $u );
112
		if ($finalize)
113
			$controller->finalize ();
114
	}
115
116
	public static function runAsString($u, $initialize = true, $finalize = true) {
117
		\ob_start ();
118
		self::runAction ( $u, $initialize, $finalize );
119
		return \ob_get_clean ();
120
	}
121
122
	private static function callController(Controller $controller, $u) {
123
		$urlSize = sizeof ( $u );
124
		switch ($urlSize) {
125
			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...
126
				$controller->index ();
127
				break;
128
			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...
129
				$action = $u [1];
130
				// Appel de la méthode (2ème élément du tableau)
131
				if (\method_exists ( $controller, $action )) {
132
					$controller->$action ();
133
				} else {
134
					print "La méthode `{$action}` n'existe pas sur le contrôleur `" . $u [0] . "`<br/>";
135
				}
136
				break;
137
			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...
138
				// Appel de la méthode en lui passant en paramètre le reste du tableau
139
				\call_user_func_array ( array ($controller,$u [1] ), array_slice ( $u, 2 ) );
140
				break;
141
		}
142
	}
143
144
	public static function getConfig() {
145
		return self::$config;
146
	}
147
148
	public static function setConfig($config) {
149
		self::$config = $config;
150
	}
151
152
	private static function needsKeyInConfigArray(&$result, $array, $needs) {
153
		foreach ( $needs as $need ) {
154
			if (! isset ( $array [$need] ) || UString::isNull ( $array [$need] )) {
155
				$result [] = $need;
156
			}
157
		}
158
	}
159
160
	public static function checkDbConfig() {
161
		$config = self::$config;
162
		$result = [ ];
163
		$needs = [ "type","dbName","serverName" ];
164
		if (! isset ( $config ["database"] )) {
165
			$result [] = "database";
166
		} else {
167
			self::needsKeyInConfigArray ( $result, $config ["database"], $needs );
168
		}
169
		return $result;
170
	}
171
172
	public static function checkModelsConfig() {
173
		$config = self::$config;
174
		$result = [ ];
175
		if (! isset ( $config ["mvcNS"] )) {
176
			$result [] = "mvcNS";
177
		} else {
178
			self::needsKeyInConfigArray ( $result, $config ["mvcNS"], [ "models" ] );
179
		}
180
		return $result;
181
	}
182
183
	public static function getModelsDir() {
184
		return self::$config ["mvcNS"] ["models"];
185
	}
186
187
	public static function getModelsCompletePath() {
188
		return ROOT . DS . self::getModelsDir ();
189
	}
190
191
	public static function errorHandler($message = "", $code = 0, $severity = 1, $filename = null, int $lineno = 0, $previous = NULL) {
192
		if (\error_reporting () == 0) {
193
			return;
194
		}
195
		if (\error_reporting () & $severity) {
196
			throw new \ErrorException ( $message, 0, $severity, $filename, $lineno, $previous );
197
		}
198
	}
199
200
	public static function getController() {
201
		return self::$controller;
202
	}
203
	
204
	public static function getControllerSimpleName() {
205
		return (new \ReflectionClass(self::$controller))->getShortName();
206
	}
207
	
208
	public static function getViewNameFileExtension(){
209
		return "html";
210
	}
211
212
	public static function getAction() {
213
		return self::$action;
214
	}
215
216
	public static function getFrameworkDir() {
217
		return \dirname ( __FILE__ );
218
	}
219
220
	public static function getApplicationDir() {
221
		return \dirname ( ROOT );
222
	}
223
	
224
	public static function getApplicationName() {
225
		return basename(\dirname ( ROOT ));
226
	}
227
	
228
	public static function reloadConfig(){
229
		$appDir=\dirname ( ROOT );
230
		$filename=$appDir."/app/config/config.php";
231
		self::$config=include($filename);
232
		self::startTemplateEngine(self::$config);
233
		return self::$config;
234
	}
235
	
236
	public static function saveConfig($content){
237
		$appDir=\dirname ( ROOT );
238
		$filename=$appDir."/app/config/config.php";
239
		$oldFilename=$appDir."/app/config/config.old.php";
240
		if (!file_exists($filename) || copy($filename, $oldFilename)) {
241
			return UFileSystem::save($filename,$content);
242
		}
243
		return false;
244
	}
245
}
246