Completed
Push — master ( 707e60...bec0f5 )
by Jean-Christophe
01:22
created

Startup   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 180
Duplicated Lines 1.11 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 43
c 0
b 0
f 0
lcom 1
cbo 3
dl 2
loc 180
rs 8.3157

15 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 22 4
A getNS() 0 8 3
A setCtrlNS() 0 3 1
A parseUrl() 2 10 3
B startTemplateEngine() 0 17 5
C runAction() 0 24 7
A runAsString() 0 5 1
B callController() 0 25 5
A getConfig() 0 3 1
A needsKeyInConfigArray() 0 7 4
A checkDbConfig() 0 11 2
A checkModelsConfig() 0 10 2
A getModelsDir() 0 3 1
A getModelsCompletePath() 0 3 1
A errorHandler() 0 8 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 micro\controllers;
4
5
use micro\utils\StrUtils;
6
use micro\views\engine\TemplateEngine;
7
8
class Startup {
9
	public static $urlParts;
10
	private static $config;
11
	private static $ctrlNS;
12
13
	public static function run(array &$config, $url) {
14
		self::$config=$config;
15
		self::startTemplateEngine($config);
16
17
		session_start();
18
19
		$u=self::parseUrl($url);
20
		if (($ru=Router::getRoute($url)) !== false) {
21
			if (\is_array($ru))
22
				self::runAction($ru);
23
			else
24
				echo $ru;
25
		} else {
26
			self::setCtrlNS();
27
			$u[0]=self::$ctrlNS . $u[0];
28
			if (\class_exists($u[0])) {
29
				self::runAction($u);
30
			} else {
31
				print "Le contrôleur `" . $u[0] . "` n'existe pas <br/>";
32
			}
33
		}
34
	}
35
36
	public static function getNS($part="controllers") {
37
		$config=self::$config;
38
		$ns=$config["mvcNS"][$part];
39
		if ($ns !== "" && $ns !== null) {
40
			$ns.="\\";
41
		}
42
		return $ns;
43
	}
44
45
	private static function setCtrlNS() {
46
		self::$ctrlNS=self::getNS();
47
	}
48
49
	private static function parseUrl(&$url) {
50
		if (!$url) {
51
			$url="_default";
52
		}
53 View Code Duplication
		if (StrUtils::endswith($url, "/"))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
			$url=\substr($url, 0, strlen($url) - 1);
55
		self::$urlParts=\explode("/", $url);
56
57
		return self::$urlParts;
58
	}
59
60
	private static function startTemplateEngine($config) {
61
		try {
62
			$engineOptions=array ('cache' => ROOT . DS . "views/cache/" );
63
			if (isset($config["templateEngine"])) {
64
				$templateEngine=$config["templateEngine"];
65
				if (isset($config["templateEngineOptions"])) {
66
					$engineOptions=$config["templateEngineOptions"];
67
				}
68
				$engine=new $templateEngine($engineOptions);
69
				if ($engine instanceof TemplateEngine) {
70
					self::$config["templateEngine"]=$engine;
71
				}
72
			}
73
		} catch ( \Exception $e ) {
74
			echo $e->getTraceAsString();
75
		}
76
	}
77
78
	public static function runAction($u, $initialize=true, $finalize=true) {
79
		$config=self::getConfig();
80
		$ctrl=$u[0];
81
		$controller=new $ctrl();
82
		if (!$controller instanceof Controller) {
83
			print "`{$u[0]}` n'est pas une instance de contrôleur.`<br/>";
84
			return;
85
		}
86
		// Dependency injection
87
		if (\array_key_exists("di", $config)) {
88
			$di=$config["di"];
89
			if (\is_array($di)) {
90
				foreach ( $di as $k => $v ) {
91
					$controller->$k=$v();
92
				}
93
			}
94
		}
95
96
		if ($initialize)
97
			$controller->initialize();
98
		self::callController($controller, $u);
99
		if ($finalize)
100
			$controller->finalize();
101
	}
102
103
	public static function runAsString($u, $initialize=true, $finalize=true) {
104
		\ob_start();
105
		self::runAction($u, $initialize, $finalize);
106
		return \ob_get_clean();
107
	}
108
109
	private static function callController(Controller $controller, $u) {
110
		$urlSize=sizeof($u);
111
		try {
112
			switch($urlSize) {
113
				case 1:
114
					$controller->index();
115
					break;
116
				case 2:
117
					$action=$u[1];
118
					// Appel de la méthode (2ème élément du tableau)
119
					if (\method_exists($controller, $action)) {
120
						$controller->$action();
121
					} else {
122
						print "La méthode `{$action}` n'existe pas sur le contrôleur `" . $u[0] . "`<br/>";
123
					}
124
					break;
125
				default:
126
					// Appel de la méthode en lui passant en paramètre le reste du tableau
127
					\call_user_func_array(array ($controller,$u[1] ), array_slice($u, 2));
128
					break;
129
			}
130
		} catch ( \Exception $e ) {
131
			print "Error!: " . $e->getMessage() . "<br/>";
132
		}
133
	}
134
135
	public static function getConfig() {
136
		return self::$config;
137
	}
138
139
140
	private static function needsKeyInConfigArray(&$result,$array,$needs){
141
		foreach ($needs as $need){
142
			if(!isset($array[$need]) || StrUtils::isNull($array[$need])){
143
				$result[]=$need;
144
			}
145
		}
146
	}
147
148
	public static function checkDbConfig(){
149
		$config=self::$config;
150
		$result=[];
151
		$needs=["type","dbName","serverName"];
152
		if(!isset($config["database"])){
153
			$result[]="database";
154
		}else{
155
			self::needsKeyInConfigArray($result, $config["database"], $needs);
156
		}
157
		return $result;
158
	}
159
160
	public static function checkModelsConfig(){
161
		$config=self::$config;
162
		$result=[];
163
		if(!isset($config["mvcNS"])){
164
			$result[]="mvcNS";
165
		}else{
166
			self::needsKeyInConfigArray($result, $config["mvcNS"], ["models"]);
167
		}
168
		return $result;
169
	}
170
171
	public static function getModelsDir() {
172
		return self::$config["mvcNS"]["models"];
173
	}
174
175
	public static function getModelsCompletePath() {
176
		return ROOT.DS.self::getModelsDir();
177
	}
178
179
	public static function errorHandler($message = "",$code = 0,$severity = 1 ,$filename =null, int $lineno = 0,$previous = NULL) {
1 ignored issue
show
Unused Code introduced by
The parameter $code is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $previous is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
180
		if (\error_reporting() == 0) {
181
			return;
182
		}
183
		if (\error_reporting() & $severity) {
184
			throw new \ErrorException($message, 0, $severity, $filename, $lineno);
185
		}
186
	}
187
}
188