Passed
Push — master ( 70ce04...9471d7 )
by Jean-Christophe
03:03
created

Startup   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 109
dl 0
loc 190
ccs 0
cts 159
cp 0
rs 8.72
c 0
b 0
f 0
wmc 46

19 Methods

Rating   Name   Duplication   Size   Complexity  
A getController() 0 2 1
A getApplicationName() 0 2 1
A run() 0 6 2
A getControllerSimpleName() 0 2 1
A callController() 0 19 4
A errorHandler() 0 6 3
A getFrameworkDir() 0 2 1
A parseUrl() 0 9 3
A _preRunAction() 0 6 2
A runAsString() 0 4 1
A startTemplateEngine() 0 12 4
B runAction() 0 25 7
A getViewNameFileExtension() 0 2 1
A getAction() 0 2 1
A runCallable() 0 12 4
A forward() 0 16 4
A getApplicationDir() 0 2 1
A getActionParams() 0 2 1
A injectDependences() 0 6 4

How to fix   Complexity   

Complex Class

Complex classes like Startup often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Startup, and based on these observations, apply Extract Interface, too.

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