Completed
Push — master ( 5b2faf...9fc245 )
by Jean-Christophe
01:54
created

ControllerParser::asArray()   C

Complexity

Conditions 8
Paths 27

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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