Completed
Push — master ( 1f65a3...0feaa6 )
by Jean-Christophe
01:28
created

ControllerParser   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 162
Duplicated Lines 4.94 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 48
c 0
b 0
f 0
lcom 1
cbo 3
dl 8
loc 162
rs 8.4864

8 Methods

Rating   Name   Duplication   Size   Complexity  
C parse() 0 23 11
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

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