Completed
Push — master ( 0feaa6...f4afa6 )
by Jean-Christophe
01:33
created

ControllerParser   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 173
Duplicated Lines 4.62 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 51
c 0
b 0
f 0
lcom 1
cbo 3
dl 8
loc 173
rs 8.3206

9 Methods

Rating   Name   Duplication   Size   Complexity  
C parse() 0 29 13
A generateRouteAnnotationFromMethod() 0 5 1
B getPathFromMethod() 0 21 5
B cleanpath() 0 10 7
C asArray() 0 25 8
B parseRouteArray() 0 20 5
D addParamsPath() 8 37 9
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 micro\cache\parser;
4
5
use micro\orm\parser\Reflexion;
6
use micro\utils\StrUtils;
7
use micro\annotations\router\RouteAnnotation;
8
use micro\cache\ClassUtils;
9
10
class ControllerParser {
11
	private $controllerClass;
12
	private $mainRouteClass;
13
	private $routesMethods=[ ];
14
	private $rest=false;
15
16
	private static $excludeds=["__construct","isValid","initialize","finalize","onInvalidControl","loadView","forward"];
17
18
19
	public function parse($controllerClass) {
20
		$this->controllerClass=$controllerClass;
21
		$reflect=new \ReflectionClass($controllerClass);
22
		if (!$reflect->isAbstract() && $reflect->isSubclassOf("micro\controllers\Controller")) {
23
			$instance=new $controllerClass();
24
			$annotsClass=Reflexion::getAnnotationClass($controllerClass, "@route");
25
			$restAnnotsClass=Reflexion::getAnnotationClass($controllerClass, "@rest");
26
			$this->rest=\sizeof($restAnnotsClass)>0;
27
			if (\sizeof($annotsClass) > 0)
28
				$this->mainRouteClass=$annotsClass[0];
29
			$methods=Reflexion::getMethods($instance, \ReflectionMethod::IS_PUBLIC);
30
			foreach ( $methods as $method ) {
31
				$annots=Reflexion::getAnnotationsMethod($controllerClass, $method->name, "@route");
32
				if ($annots !== false){
33
					foreach ($annots as $annot){
34
						if(StrUtils::isNull($annot->path)){
35
							$annot->path="/".$method->getName();
1 ignored issue
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
36
						}
37
					}
38
					$this->routesMethods[$method->name]=[ "annotations" => $annots,"method" => $method ];
39
				}else{
40
					if($this->rest && isset($this->mainRouteClass)){
41
						if($method->class!=='micro\\controllers\\Controller' && \array_search($method->name, self::$excludeds)===false && !StrUtils::startswith($method->name, "_"))
42
							$this->routesMethods[$method->name]=[ "annotations" => $this->generateRouteAnnotationFromMethod($method),"method" => $method ];
43
					}
44
				}
45
			}
46
		}
47
	}
48
49
	private function generateRouteAnnotationFromMethod(\ReflectionMethod $method){
50
		$annot=new RouteAnnotation();
51
		$annot->path=self::getPathFromMethod($method);
52
		return [$annot];
53
	}
54
55
	private static function getPathFromMethod(\ReflectionMethod $method){
56
		$methodName=$method->getName();
1 ignored issue
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
57
		if($methodName==="index"){
58
			$pathParts=["(index/)?"];
59
		}else{
60
			$pathParts=[$methodName];
61
		}
62
		$parameters=$method->getParameters();
63
		foreach ($parameters as $parameter){
64
			if($parameter->isVariadic()){
65
				$pathParts[]='{...'.$parameter->getName().'}';
1 ignored issue
show
Bug introduced by
Consider using $parameter->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
66
				return "/".\implode("/", $pathParts);
67
			}
68
			if(!$parameter->isOptional()){
69
				$pathParts[]='{'.$parameter->getName().'}';
1 ignored issue
show
Bug introduced by
Consider using $parameter->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
70
			}else{
71
				$pathParts[\sizeof($pathParts)-1].='{~'.$parameter->getName().'}';
1 ignored issue
show
Bug introduced by
Consider using $parameter->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
72
			}
73
		}
74
		return "/".\implode("/", $pathParts);
75
	}
76
77
	private static function cleanpath($prefix, $path="") {
78
		if (!StrUtils::endswith($prefix, "/"))
79
			$prefix=$prefix . "/";
80
		if ($path !== "" && StrUtils::startswith($path, "/"))
81
			$path=\substr($path, 1);
82
		$path=$prefix . $path;
83
		if (!StrUtils::endswith($path, "/") && !StrUtils::endswith($path, '(.*?)') && !StrUtils::endswith($path, "(index/)?"))
84
			$path=$path."/";
85
		return $path;
86
	}
87
88
	public function asArray() {
89
		$result=[ ];
90
		$prefix="";
91
		$httpMethods=false;
92
		if ($this->mainRouteClass) {
93
			if (isset($this->mainRouteClass->path))
94
				$prefix=$this->mainRouteClass->path;
95
			if (isset($this->mainRouteClass->methods)) {
96
				$httpMethods=$this->mainRouteClass->methods;
97
				if ($httpMethods !== null) {
98
					if (\is_string($httpMethods))
99
						$httpMethods=[ $httpMethods ];
100
				}
101
			}
102
		}
103
		foreach ( $this->routesMethods as $method => $arrayAnnotsMethod ) {
104
			$routeAnnotations=$arrayAnnotsMethod["annotations"];
105
106
			foreach ( $routeAnnotations as $routeAnnotation ) {
107
				$params=[ "path" => $routeAnnotation->path,"methods" => $routeAnnotation->methods,"name" => $routeAnnotation->name,"cache" => $routeAnnotation->cache,"duration" => $routeAnnotation->duration ];
108
				self::parseRouteArray($result, $this->controllerClass,$params,$arrayAnnotsMethod["method"], $method, $prefix, $httpMethods);
109
			}
110
		}
111
		return $result;
112
	}
113
114
	public static function parseRouteArray(&$result, $controllerClass, $routeArray, \ReflectionMethod $method, $methodName, $prefix="", $httpMethods=NULL) {
115
		if (!isset($routeArray["path"])) {
116
			$routeArray["path"]=self::getPathFromMethod($method);
117
		}
118
		$pathParameters=self::addParamsPath($routeArray["path"], $method);
119
		$name=$routeArray["name"];
120
		$cache=$routeArray["cache"];
121
		$duration=$routeArray["duration"];
122
		$path=$pathParameters["path"];
123
		$parameters=$pathParameters["parameters"];
124
		$path=self::cleanpath($prefix, $path);
125
		$controllerClass=ClassUtils::cleanClassname($controllerClass);
126
		if (isset($routeArray["methods"]) && \is_array($routeArray["methods"])) {
127
			self::createRouteMethod($result, $controllerClass, $path, $routeArray["methods"], $methodName, $parameters, $name, $cache, $duration);
128
		} elseif (\is_array($httpMethods)) {
129
			self::createRouteMethod($result, $controllerClass, $path, $httpMethods, $methodName, $parameters, $name, $cache, $duration);
130
		} else {
131
			$result[$path]=[ "controller" => $controllerClass,"action" => $methodName,"parameters" => $parameters,"name" => $name,"cache" => $cache,"duration" => $duration ];
132
		}
133
	}
134
135
	public static function addParamsPath($path, \ReflectionMethod $method) {
136
		$parameters=[ ];
137
		$hasOptionnal=false;
138
		preg_match_all('@\{(\.\.\.|\~)?(.+?)\}@s', $path, $matches);
139
		if (isset($matches[2]) && \sizeof($matches[2]) > 0) {
140
			$path=\preg_quote($path);
141
			$params=Reflexion::getMethodParameters($method);
142
			$index=0;
143
			foreach ( $matches[2] as $paramMatch ) {
144
				$find=\array_search($paramMatch, $params);
145
				if ($find !== false) {
146
					if(isset($matches[1][$index])){
147
						if($matches[1][$index]==="..."){
148
							$parameters[]="*";
149
							$path=\str_replace("\{\.\.\." . $paramMatch . "\}", "(.*?)", $path);
150
						}elseif($matches[1][$index]==="~"){
151
							$parameters[]="~".$find;
152
							$path=\str_replace("\{~" . $paramMatch . "\}", "", $path);
153
							$hasOptionnal=true;
154 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...
155
							$parameters[]=$find;
156
							$path=\str_replace("\{" . $paramMatch . "\}", "(.+?)", $path);
157
						}
158 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...
159
						$parameters[]=$find;
160
						$path=\str_replace("\{" . $paramMatch . "\}", "(.+?)", $path);
161
					}
162
				} else {
163
					throw new \Exception("{$paramMatch} is not a parameter of the method " . $method->name);
164
				}
165
				$index++;
166
			}
167
		}
168
		if($hasOptionnal)
169
			$path.="/(.*?)";
170
		return [ "path" => $path,"parameters" => $parameters ];
171
	}
172
173
	private static function createRouteMethod(&$result, $controllerClass, $path, $httpMethods, $method, $parameters, $name, $cache, $duration) {
174
		foreach ( $httpMethods as $httpMethod ) {
175
			$result[$path][$httpMethod]=[ "controller" => $controllerClass,"action" => $method,"parameters" => $parameters,"name" => $name,"cache" => $cache,"duration" => $duration ];
176
		}
177
	}
178
179
	public function isRest(){
180
		return $this->rest;
181
	}
182
}
183