Completed
Push — master ( 3845e2...5afe3b )
by Jean-Christophe
02:10
created

ControllerParser   C

Complexity

Total Complexity 57

Size/Duplication

Total Lines 195
Duplicated Lines 4.1 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 57
lcom 1
cbo 3
dl 8
loc 195
rs 5.04
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
C parse() 0 43 16
A generateRouteAnnotationFromMethod() 0 5 1
A getPathFromMethod() 0 21 5
B cleanpath() 0 10 7
B asArray() 0 25 8
B parseRouteArray() 0 22 6
B addParamsPath() 0 26 7
A scanParam() 8 18 4
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 Ubiquity\cache\parser;
4
5
use Ubiquity\orm\parser\Reflexion;
6
use Ubiquity\utils\base\UString;
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
			try{
25
			$annotsClass=Reflexion::getAnnotationClass($controllerClass, "@route");
26
			$restAnnotsClass=Reflexion::getAnnotationClass($controllerClass, "@rest");
27
			}catch (\Exception $e){
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
28
				
29
			}
30
			$this->rest=\sizeof($restAnnotsClass) > 0;
0 ignored issues
show
Bug introduced by
The variable $restAnnotsClass does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

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