Completed
Push — master ( bab95f...e5619f )
by Jean-Christophe
01:46
created

ControllerParser   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 214
Duplicated Lines 3.74 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 63
lcom 1
cbo 3
dl 8
loc 214
rs 3.36
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
C parse() 0 46 16
A generateRouteAnnotationFromMethod() 0 5 1
A getPathFromMethod() 0 21 5
A parseMethodPath() 0 14 6
B cleanpath() 0 11 7
B asArray() 0 25 8
B parseRouteArray() 0 22 6
B addParamsPath() 0 26 7
A scanParam() 8 18 4
A createRouteMethod() 0 5 2
A isRest() 0 3 1

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 ControllerParser 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 ControllerParser, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Ubiquity\cache\parser;
4
5
use Ubiquity\orm\parser\Reflexion;
6
use Ubiquity\utils\base\UString;
7
use Ubiquity\annotations\router\RouteAnnotation;
8
use Ubiquity\cache\ClassUtils;
9
10
class ControllerParser {
11
	private $controllerClass;
12
	private $mainRouteClass;
13
	private $routesMethods=[ ];
14
	private $rest=false;
15
	private static $excludeds=[ "__construct","isValid","initialize","finalize","onInvalidControl","loadView","forward","redirectToRoute" ];
16
17
	public function parse($controllerClass) {
18
		$automated=false;
19
		$inherited=false;
20
		$this->controllerClass=$controllerClass;
21
		$restAnnotsClass=[];$annotsClass=[];
22
		$reflect=new \ReflectionClass($controllerClass);
23
		if (!$reflect->isAbstract() && $reflect->isSubclassOf("Ubiquity\controllers\Controller")) {
24
			$instance=new $controllerClass();
25
			try{
26
			$annotsClass=Reflexion::getAnnotationClass($controllerClass, "@route");
27
			$restAnnotsClass=Reflexion::getAnnotationClass($controllerClass, "@rest");
28
			}catch (\Exception $e){
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
29
				
30
			}
31
			$this->rest=\sizeof($restAnnotsClass) > 0;
32
			if (\sizeof($annotsClass) > 0) {
33
				$this->mainRouteClass=$annotsClass[0];
34
				$inherited=$this->mainRouteClass->inherited;
35
				$automated=$this->mainRouteClass->automated;
36
			}
37
			$methods=Reflexion::getMethods($instance, \ReflectionMethod::IS_PUBLIC);
38
			foreach ( $methods as $method ) {
39
				if ($method->getDeclaringClass()->getName() === $controllerClass || $inherited) {
1 ignored issue
show
introduced by
Consider using $method->class. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
40
					try{
41
						$annots=Reflexion::getAnnotationsMethod($controllerClass, $method->name, ["@route","@get","@post"]);
42
						if (sizeof($annots)>0) {
43
							foreach ( $annots as $annot ) {
44
								if (UString::isNull($annot->path)) {
45
									$newAnnot=$this->generateRouteAnnotationFromMethod($method);
46
									$annot->path=$newAnnot[0]->path;
47
								}else{
48
									$annot->path=$this->parseMethodPath($method, $annot->path);
49
								}
50
							}
51
							$this->routesMethods[$method->name]=[ "annotations" => $annots,"method" => $method ];
52
						} else {
53
							if ($automated) {
54
								if ($method->class !== 'Ubiquity\\controllers\\Controller' && \array_search($method->name, self::$excludeds) === false && !UString::startswith($method->name, "_"))
55
									$this->routesMethods[$method->name]=[ "annotations" => $this->generateRouteAnnotationFromMethod($method),"method" => $method ];
56
							}
57
						}
58
					}catch(\Exception $e){}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
59
				}
60
			}
61
		}
62
	}
63
64
	private function generateRouteAnnotationFromMethod(\ReflectionMethod $method) {
65
		$annot=new RouteAnnotation();
66
		$annot->path=self::getPathFromMethod($method);
67
		return [ $annot ];
68
	}
69
70
	private static function getPathFromMethod(\ReflectionMethod $method) {
71
		$methodName=$method->getName();
72
		if ($methodName === "index") {
73
			$pathParts=[ "(index/)?" ];
74
		} else {
75
			$pathParts=[ $methodName ];
76
		}
77
		$parameters=$method->getParameters();
78
		foreach ( $parameters as $parameter ) {
79
			if ($parameter->isVariadic()) {
80
				$pathParts[]='{...' . $parameter->getName() . '}';
81
				return "/" . \implode("/", $pathParts);
82
			}
83
			if (!$parameter->isOptional()) {
84
				$pathParts[]='{' . $parameter->getName() . '}';
85
			} else {
86
				$pathParts[\sizeof($pathParts) - 1].='{~' . $parameter->getName() . '}';
87
			}
88
		}
89
		return "/" . \implode("/", $pathParts);
90
	}
91
	
92
	private static function parseMethodPath(\ReflectionMethod $method,$path){
93
		if($path==null || $path==='')
94
			return;
95
		$parameters=$method->getParameters();
96
		foreach ( $parameters as $parameter ) {
97
			$name=$parameter->getName();
98
			if ($parameter->isVariadic()) {
99
				$path=str_replace('{'.$name.'}', '{...' . $name . '}',$path);
100
			}elseif ($parameter->isOptional()) {
101
				$path=str_replace('{'.$name.'}', '{~' . $name . '}',$path);
102
			}
103
		}
104
		return $path;
105
	}
106
107
	private static function cleanpath($prefix, $path="") {
108
		$path=str_replace("//", "/", $path);
109
		if (!UString::endswith($prefix, "/"))
110
			$prefix=$prefix . "/";
111
		if ($path !== "" && UString::startswith($path, "/"))
112
			$path=\substr($path, 1);
113
		$path=$prefix . $path;
114
		if (!UString::endswith($path, "/") && !UString::endswith($path, '(.*?)') && !UString::endswith($path, "(index/)?"))
115
			$path=$path . "/";
116
		return $path;
117
	}
118
119
	public function asArray() {
120
		$result=[ ];
121
		$prefix="";
122
		$httpMethods=false;
123
		if ($this->mainRouteClass) {
124
			if (isset($this->mainRouteClass->path))
125
				$prefix=$this->mainRouteClass->path;
126
			if (isset($this->mainRouteClass->methods)) {
127
				$httpMethods=$this->mainRouteClass->methods;
128
				if ($httpMethods !== null) {
129
					if (\is_string($httpMethods))
130
						$httpMethods=[ $httpMethods ];
131
				}
132
			}
133
		}
134
		foreach ( $this->routesMethods as $method => $arrayAnnotsMethod ) {
135
			$routeAnnotations=$arrayAnnotsMethod["annotations"];
136
137
			foreach ( $routeAnnotations as $routeAnnotation ) {
138
				$params=[ "path" => $routeAnnotation->path,"methods" => $routeAnnotation->methods,"name" => $routeAnnotation->name,"cache" => $routeAnnotation->cache,"duration" => $routeAnnotation->duration,"requirements" => $routeAnnotation->requirements ];
139
				self::parseRouteArray($result, $this->controllerClass, $params, $arrayAnnotsMethod["method"], $method, $prefix, $httpMethods);
140
			}
141
		}
142
		return $result;
143
	}
144
145
	public static function parseRouteArray(&$result, $controllerClass, $routeArray, \ReflectionMethod $method, $methodName, $prefix="", $httpMethods=NULL) {
146
		if (!isset($routeArray["path"])) {
147
			$routeArray["path"]=self::getPathFromMethod($method);
148
		}
149
		$pathParameters=self::addParamsPath($routeArray["path"], $method, $routeArray["requirements"]);
150
		$name=$routeArray["name"];
151
		if (!isset($name)) {
152
			$name=UString::cleanAttribute(ClassUtils::getClassSimpleName($controllerClass) . "_" . $methodName);
153
		}
154
		$cache=$routeArray["cache"];
155
		$duration=$routeArray["duration"];
156
		$path=$pathParameters["path"];
157
		$parameters=$pathParameters["parameters"];
158
		$path=self::cleanpath($prefix, $path);
159
		if (isset($routeArray["methods"]) && \is_array($routeArray["methods"])) {
160
			self::createRouteMethod($result, $controllerClass, $path, $routeArray["methods"], $methodName, $parameters, $name, $cache, $duration);
161
		} elseif (\is_array($httpMethods)) {
162
			self::createRouteMethod($result, $controllerClass, $path, $httpMethods, $methodName, $parameters, $name, $cache, $duration);
163
		} else {
164
			$result[$path]=[ "controller" => $controllerClass,"action" => $methodName,"parameters" => $parameters,"name" => $name,"cache" => $cache,"duration" => $duration];
165
		}
166
	}
167
168
	public static function addParamsPath($path, \ReflectionMethod $method, $requirements) {
169
		$parameters=[ ];
170
		$hasOptional=false;
171
		preg_match_all('@\{(\.\.\.|\~)?(.+?)\}@s', $path, $matches);
172
		if (isset($matches[2]) && \sizeof($matches[2]) > 0) {
173
			$path=\preg_quote($path);
174
			$params=Reflexion::getMethodParameters($method);
175
			$index=0;
176
			foreach ( $matches[2] as $paramMatch ) {
177
				$find=\array_search($paramMatch, $params);
178
				if ($find !== false) {
179
					$requirement='.+?';
180
					if (isset($requirements[$paramMatch])) {
181
						$requirement=$requirements[$paramMatch];
182
					}
183
					self::scanParam($parameters, $hasOptional, $matches, $index, $paramMatch, $find, $path, $requirement);
184
				} else {
185
					throw new \Exception("{$paramMatch} is not a parameter of the method " . $method->name);
186
				}
187
				$index++;
188
			}
189
		}
190
		if ($hasOptional)
191
			$path.="/(.*?)";
192
		return [ "path" => $path,"parameters" => $parameters ];
193
	}
194
195
	private static function scanParam(&$parameters, &$hasOptional, $matches, $index, $paramMatch, $find, &$path, $requirement) {
196
		if (isset($matches[1][$index])) {
197
			if ($matches[1][$index] === "...") {
198
				$parameters[]="*";
199
				$path=\str_replace("\{\.\.\." . $paramMatch . "\}", "(.*?)", $path);
200
			} elseif ($matches[1][$index] === "~") {
201
				$parameters[]="~" . $find;
202
				$path=\str_replace("\{~" . $paramMatch . "\}", "", $path);
203
				$hasOptional=true;
204 View Code Duplication
			} else {
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...
205
				$parameters[]=$find;
206
				$path=\str_replace("\{" . $paramMatch . "\}", "({$requirement})", $path);
207
			}
208 View Code Duplication
		} else {
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...
209
			$parameters[]=$find;
210
			$path=\str_replace("\{" . $paramMatch . "\}", "({$requirement})", $path);
211
		}
212
	}
213
214
	private static function createRouteMethod(&$result, $controllerClass, $path, $httpMethods, $method, $parameters, $name, $cache, $duration) {
215
		foreach ( $httpMethods as $httpMethod ) {
216
			$result[$path][$httpMethod]=[ "controller" => $controllerClass,"action" => $method,"parameters" => $parameters,"name" => $name,"cache" => $cache,"duration" => $duration ];
217
		}
218
	}
219
220
	public function isRest() {
221
		return $this->rest;
222
	}
223
}
224