Completed
Push — master ( 4e6026...e0b9fa )
by Jean-Christophe
01:30
created

ControllerParser::parseRouteArray()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 20
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 17
nc 6
nop 7
1
<?php
2
3
namespace Ubiquity\cache\parser;
4
5
use Ubiquity\orm\parser\Reflexion;
6
use Ubiquity\utils\StrUtils;
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
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
							$newAnnot=$this->generateRouteAnnotationFromMethod($method);
36
							$annot->path=$newAnnot[0]->path;
37
						}
38
					}
39
					$this->routesMethods[$method->name]=[ "annotations" => $annots,"method" => $method ];
40
				}else{
41
					if($this->rest && isset($this->mainRouteClass)){
42
						if($method->class!=='micro\\controllers\\Controller' && \array_search($method->name, self::$excludeds)===false && !StrUtils::startswith($method->name, "_"))
43
							$this->routesMethods[$method->name]=[ "annotations" => $this->generateRouteAnnotationFromMethod($method),"method" => $method ];
44
					}
45
				}
46
			}
47
		}
48
	}
49
50
	private function generateRouteAnnotationFromMethod(\ReflectionMethod $method){
51
		$annot=new RouteAnnotation();
52
		$annot->path=self::getPathFromMethod($method);
53
		return [$annot];
54
	}
55
56
	private static function getPathFromMethod(\ReflectionMethod $method){
57
		$methodName=$method->getName();
58
		if($methodName==="index"){
59
			$pathParts=["(index/)?"];
60
		}else{
61
			$pathParts=[$methodName];
62
		}
63
		$parameters=$method->getParameters();
64
		foreach ($parameters as $parameter){
65
			if($parameter->isVariadic()){
66
				$pathParts[]='{...'.$parameter->getName().'}';
67
				return "/".\implode("/", $pathParts);
68
			}
69
			if(!$parameter->isOptional()){
70
				$pathParts[]='{'.$parameter->getName().'}';
71
			}else{
72
				$pathParts[\sizeof($pathParts)-1].='{~'.$parameter->getName().'}';
73
			}
74
		}
75
		return "/".\implode("/", $pathParts);
76
	}
77
78
	private static function cleanpath($prefix, $path="") {
79
		if (!StrUtils::endswith($prefix, "/"))
80
			$prefix=$prefix . "/";
81
		if ($path !== "" && StrUtils::startswith($path, "/"))
82
			$path=\substr($path, 1);
83
		$path=$prefix . $path;
84
		if (!StrUtils::endswith($path, "/") && !StrUtils::endswith($path, '(.*?)') && !StrUtils::endswith($path, "(index/)?"))
85
			$path=$path."/";
86
		return $path;
87
	}
88
89
	public function asArray() {
90
		$result=[ ];
91
		$prefix="";
92
		$httpMethods=false;
93
		if ($this->mainRouteClass) {
94
			if (isset($this->mainRouteClass->path))
95
				$prefix=$this->mainRouteClass->path;
96
			if (isset($this->mainRouteClass->methods)) {
97
				$httpMethods=$this->mainRouteClass->methods;
98
				if ($httpMethods !== null) {
99
					if (\is_string($httpMethods))
100
						$httpMethods=[ $httpMethods ];
101
				}
102
			}
103
		}
104
		foreach ( $this->routesMethods as $method => $arrayAnnotsMethod ) {
105
			$routeAnnotations=$arrayAnnotsMethod["annotations"];
106
107
			foreach ( $routeAnnotations as $routeAnnotation ) {
108
				$params=[ "path" => $routeAnnotation->path,"methods" => $routeAnnotation->methods,"name" => $routeAnnotation->name,"cache" => $routeAnnotation->cache,"duration" => $routeAnnotation->duration ];
109
				self::parseRouteArray($result, $this->controllerClass,$params,$arrayAnnotsMethod["method"], $method, $prefix, $httpMethods);
110
			}
111
		}
112
		return $result;
113
	}
114
115
	public static function parseRouteArray(&$result, $controllerClass, $routeArray, \ReflectionMethod $method, $methodName, $prefix="", $httpMethods=NULL) {
116
		if (!isset($routeArray["path"])) {
117
			$routeArray["path"]=self::getPathFromMethod($method);
118
		}
119
		$pathParameters=self::addParamsPath($routeArray["path"], $method);
120
		$name=$routeArray["name"];
121
		$cache=$routeArray["cache"];
122
		$duration=$routeArray["duration"];
123
		$path=$pathParameters["path"];
124
		$parameters=$pathParameters["parameters"];
125
		$path=self::cleanpath($prefix, $path);
126
		$controllerClass=ClassUtils::cleanClassname($controllerClass);
127
		if (isset($routeArray["methods"]) && \is_array($routeArray["methods"])) {
128
			self::createRouteMethod($result, $controllerClass, $path, $routeArray["methods"], $methodName, $parameters, $name, $cache, $duration);
129
		} elseif (\is_array($httpMethods)) {
130
			self::createRouteMethod($result, $controllerClass, $path, $httpMethods, $methodName, $parameters, $name, $cache, $duration);
131
		} else {
132
			$result[$path]=[ "controller" => $controllerClass,"action" => $methodName,"parameters" => $parameters,"name" => $name,"cache" => $cache,"duration" => $duration ];
133
		}
134
	}
135
136
	public static function addParamsPath($path, \ReflectionMethod $method) {
137
		$parameters=[ ];
138
		$hasOptional=false;
139
		preg_match_all('@\{(\.\.\.|\~)?(.+?)\}@s', $path, $matches);
140
		if (isset($matches[2]) && \sizeof($matches[2]) > 0) {
141
			$path=\preg_quote($path);
142
			$params=Reflexion::getMethodParameters($method);
143
			$index=0;
144
			foreach ( $matches[2] as $paramMatch ) {
145
				$find=\array_search($paramMatch, $params);
146
				if ($find !== false) {
147
					self::scanParam($parameters, $hasOptional, $matches, $index, $paramMatch, $find, $path);
148
				} else {
149
					throw new \Exception("{$paramMatch} is not a parameter of the method " . $method->name);
150
				}
151
				$index++;
152
			}
153
		}
154
		if($hasOptional)
155
			$path.="/(.*?)";
156
		return [ "path" => $path,"parameters" => $parameters ];
157
	}
158
159
	private static function scanParam(&$parameters,&$hasOptional,$matches,$index,$paramMatch,$find,&$path){
160
		if(isset($matches[1][$index])){
161
			if($matches[1][$index]==="..."){
162
				$parameters[]="*";
163
				$path=\str_replace("\{\.\.\." . $paramMatch . "\}", "(.*?)", $path);
164
			}elseif($matches[1][$index]==="~"){
165
				$parameters[]="~".$find;
166
				$path=\str_replace("\{~" . $paramMatch . "\}", "", $path);
167
				$hasOptional=true;
168 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...
169
				$parameters[]=$find;
170
				$path=\str_replace("\{" . $paramMatch . "\}", "(.+?)", $path);
171
			}
172 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...
173
			$parameters[]=$find;
174
			$path=\str_replace("\{" . $paramMatch . "\}", "(.+?)", $path);
175
		}
176
	}
177
178
	private static function createRouteMethod(&$result, $controllerClass, $path, $httpMethods, $method, $parameters, $name, $cache, $duration) {
179
		foreach ( $httpMethods as $httpMethod ) {
180
			$result[$path][$httpMethod]=[ "controller" => $controllerClass,"action" => $method,"parameters" => $parameters,"name" => $name,"cache" => $cache,"duration" => $duration ];
181
		}
182
	}
183
184
	public function isRest(){
185
		return $this->rest;
186
	}
187
}
188