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

ControllerParser::parse()   C

Complexity

Conditions 11
Paths 11

Size

Total Lines 23
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 23
rs 5.3929
cc 11
eloc 18
nc 11
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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