Passed
Branch master (60a40e)
by Alex
03:08
created
src/Collector.php 3 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      * @var array
62 62
      */
63 63
 
64
-    protected $statics  = [];
64
+    protected $statics = [];
65 65
 
66 66
     /**
67 67
      * The dynamic routes have parameters and are stored in a hashtable that every cell have
@@ -123,10 +123,10 @@  discard block
 block discarded – undo
123 123
         return new Group($group);
124 124
     }
125 125
 
126
-    public function get   ($pattern, $action) { return $this->set("get"   , $pattern, $action); }
127
-    public function post  ($pattern, $action) { return $this->set("post"  , $pattern, $action); }
128
-    public function put   ($pattern, $action) { return $this->set("put"   , $pattern, $action); }
129
-    public function patch ($pattern, $action) { return $this->set("patch" , $pattern, $action); }
126
+    public function get($pattern, $action) { return $this->set("get", $pattern, $action); }
127
+    public function post($pattern, $action) { return $this->set("post", $pattern, $action); }
128
+    public function put($pattern, $action) { return $this->set("put", $pattern, $action); }
129
+    public function patch($pattern, $action) { return $this->set("patch", $pattern, $action); }
130 130
     public function delete($pattern, $action) { return $this->set("delete", $pattern, $action); }
131 131
 
132 132
     /**
Please login to merge, or discard this patch.
Braces   +21 added lines, -11 removed lines patch added patch discarded remove patch
@@ -117,7 +117,9 @@  discard block
 block discarded – undo
117 117
             if (strpos($pattern, "{") !== false) {
118 118
                    $index = $this->getDynamicIndex($method, $pattern);
119 119
                    $this->dynamics[$index][$pattern] = $route;
120
-            } else $this->statics[$method][$pattern] = $route;
120
+            } else {
121
+            	$this->statics[$method][$pattern] = $route;
122
+            }
121 123
         }
122 124
 
123 125
         return $group;
@@ -142,8 +144,9 @@  discard block
 block discarded – undo
142 144
     public function match(array $methods, $pattern, $action)
143 145
     {
144 146
         $group = new Group;
145
-        foreach ($methods as $method)
146
-            $group->set($this->set($method, $pattern, $action));
147
+        foreach ($methods as $method) {
148
+                    $group->set($this->set($method, $pattern, $action));
149
+        }
147 150
         return $group;
148 151
     }
149 152
 
@@ -186,8 +189,9 @@  discard block
 block discarded – undo
186 189
     public function group(array $routes)
187 190
     {
188 191
         $group = new Group;
189
-        foreach ($routes as $route)
190
-            $group->set($route);
192
+        foreach ($routes as $route) {
193
+                    $group->set($route);
194
+        }
191 195
         return $group;
192 196
     }
193 197
 
@@ -202,7 +206,9 @@  discard block
 block discarded – undo
202 206
     {
203 207
         if (strpos($pattern, "{") === false) {
204 208
                unset($this->statics[$method][$pattern]);
205
-        } else unset($this->dynamics[$this->getDynamicIndex($method, $pattern)][$pattern]);
209
+        } else {
210
+        	unset($this->dynamics[$this->getDynamicIndex($method, $pattern)][$pattern]);
211
+        }
206 212
     }
207 213
 
208 214
     /**
@@ -257,7 +263,9 @@  discard block
 block discarded – undo
257 263
         if ($closingNumber !== count($segments) - 1) {
258 264
             if (preg_match("~" . self::DYNAMIC_REGEX . "(*SKIP)(*F)|\]~x", $withoutClosing)) {
259 265
                    throw new BadRouteException(BadRouteException::OPTIONAL_SEGMENTS_ON_MIDDLE);
260
-            } else throw new BadRouteException(BadRouteException::UNCLOSED_OPTIONAL_SEGMENTS);
266
+            } else {
267
+            	throw new BadRouteException(BadRouteException::UNCLOSED_OPTIONAL_SEGMENTS);
268
+            }
261 269
         }
262 270
     }
263 271
 
@@ -296,8 +304,9 @@  discard block
 block discarded – undo
296 304
     public function findStaticRoute($method, $pattern)
297 305
     {
298 306
         $method = strtolower($method);
299
-        if (isset($this->statics[$method]) && isset($this->statics[$method][$pattern]))
300
-            return $this->statics[$method][$pattern];
307
+        if (isset($this->statics[$method]) && isset($this->statics[$method][$pattern])) {
308
+                    return $this->statics[$method][$pattern];
309
+        }
301 310
         return false;
302 311
     }
303 312
 
@@ -333,8 +342,9 @@  discard block
 block discarded – undo
333 342
     public function getWildcards()
334 343
     {
335 344
         $wildcards = [];
336
-        foreach ($this->wildcards as $token => $regex)
337
-            $wildcards[substr($token, 1)] = substr($regex, 1);
345
+        foreach ($this->wildcards as $token => $regex) {
346
+                    $wildcards[substr($token, 1)] = substr($regex, 1);
347
+        }
338 348
         return $wildcards;
339 349
     }
340 350
 
Please login to merge, or discard this patch.
Indentation   +336 added lines, -336 removed lines patch added patch discarded remove patch
@@ -33,341 +33,341 @@
 block discarded – undo
33 33
 class Collector
34 34
 {
35 35
 
36
-    use Collectors\ControllerCollectorTrait;
37
-    use Collectors\ResourceCollectorTrait;
38
-
39
-    /**
40
-     * These regex define the structure of a dynamic segment in a pattern.
41
-     *
42
-     * @var string
43
-     */
44
-
45
-    const DYNAMIC_REGEX = "{\s*(\w*)\s*(?::\s*([^{}]*(?:{(?-1)}*)*))?\s*}";
46
-
47
-
48
-    /**
49
-     * All the supported http methods separated by spaces.
50
-     *
51
-     * @var string
52
-     */
53
-
54
-    const HTTP_METHODS = "get post put patch delete";
55
-
56
-    /**
57
-     * The static routes are simple stored in a multidimensional array, the first
58
-     * dimension is indexed by an http method and hold an array indexed with the patterns
59
-     * and holding the route. ex. [METHOD => [PATTERN => ROUTE]]
60
-     *
61
-     * @var array
62
-     */
63
-
64
-    protected $statics  = [];
65
-
66
-    /**
67
-     * The dynamic routes have parameters and are stored in a hashtable that every cell have
68
-     * an array with route patterns as indexes and routes as values. ex. [INDEX => [PATTERN => ROUTE]]
69
-     *
70
-     * @var array
71
-     */
72
-
73
-    protected $dynamics = [];
74
-
75
-    /**
76
-     * Some regex wildcards for easily definition of dynamic routes. ps. all keys and values must start with :
77
-     *
78
-     * @var array
79
-     */
80
-
81
-    protected $wildcards = [
82
-        ":uid"     => ":uid-[a-zA-Z0-9]",
83
-        ":slug"    => ":[a-z0-9-]",
84
-        ":string"  => ":\w",
85
-        ":int"     => ":\d",
86
-        ":integer" => ":\d",
87
-        ":float"   => ":[-+]?\d*?[.]?\d",
88
-        ":double"  => ":[-+]?\d*?[.]?\d",
89
-        ":hex"     => ":0[xX][0-9a-fA-F]",
90
-        ":octal"   => ":0[1-7][0-7]",
91
-        ":bool"    => ":1|0|true|false|yes|no",
92
-        ":boolean" => ":1|0|true|false|yes|no",
93
-    ];
94
-
95
-    /**
96
-     * @param string $method
97
-     * @param string $pattern
98
-     * @param callable $action
99
-     *
100
-     * @throws BadRouteException 
101
-     * @throws MethodNotSupportedException
102
-     *
103
-     * @return Group
104
-     */
105
-
106
-    public function set($method, $pattern, $action)
107
-    {
108
-        $method   = $this->parseMethod($method);
109
-        $patterns = $this->parsePattern($pattern);
110
-        $group    = new Group;
111
-
112
-        foreach ($patterns as $pattern)
113
-        {
114
-            $route = new Route($this, $method, $pattern, $action);
115
-            $group->setRoute($route);
116
-
117
-            if (strpos($pattern, "{") !== false) {
118
-                   $index = $this->getDynamicIndex($method, $pattern);
119
-                   $this->dynamics[$index][$pattern] = $route;
120
-            } else $this->statics[$method][$pattern] = $route;
121
-        }
122
-
123
-        return $group;
124
-    }
125
-
126
-    public function get   ($pattern, $action) { return $this->set("get"   , $pattern, $action); }
127
-    public function post  ($pattern, $action) { return $this->set("post"  , $pattern, $action); }
128
-    public function put   ($pattern, $action) { return $this->set("put"   , $pattern, $action); }
129
-    public function patch ($pattern, $action) { return $this->set("patch" , $pattern, $action); }
130
-    public function delete($pattern, $action) { return $this->set("delete", $pattern, $action); }
131
-
132
-    /**
133
-     * Insert a route into several http methods.
134
-     *
135
-     * @param string[] $methods
136
-     * @param string $pattern
137
-     * @param callable $action
138
-     *
139
-     * @return Group
140
-     */
141
-
142
-    public function match(array $methods, $pattern, $action)
143
-    {
144
-        $group = new Group;
145
-        foreach ($methods as $method)
146
-            $group->set($this->set($method, $pattern, $action));
147
-        return $group;
148
-    }
149
-
150
-    /**
151
-     * Insert a route into every http method supported.
152
-     *
153
-     * @param string $pattern
154
-     * @param callable $action
155
-     *
156
-     * @return Group
157
-     */
158
-
159
-    public function any($pattern, $action)
160
-    {
161
-        return $this->match(explode(" ", self::HTTP_METHODS), $pattern, $action);
162
-    }
163
-
164
-    /**
165
-     * Insert a route into every http method supported but the given ones.
166
-     *
167
-     * @param string $methods
168
-     * @param string $pattern
169
-     * @param callable $action
170
-     *
171
-     * @return Group
172
-     */
173
-
174
-    public function except($methods, $pattern, $action)
175
-    {
176
-        return $this->match(array_diff(explode(" ", self::HTTP_METHODS), (array) $methods), $pattern, $action);
177
-    }
178
-
179
-    /**
180
-     * Group all given routes.
181
-     *
182
-     * @param Route[] $routes
183
-     * @return Group
184
-     */
185
-
186
-    public function group(array $routes)
187
-    {
188
-        $group = new Group;
189
-        foreach ($routes as $route)
190
-            $group->set($route);
191
-        return $group;
192
-    }
193
-
194
-    /**
195
-     * Remove a route from collector.
196
-     *
197
-     * @param string $method
198
-     * @param string $pattern
199
-     */
200
-
201
-    public function forget($method, $pattern)
202
-    {
203
-        if (strpos($pattern, "{") === false) {
204
-               unset($this->statics[$method][$pattern]);
205
-        } else unset($this->dynamics[$this->getDynamicIndex($method, $pattern)][$pattern]);
206
-    }
207
-
208
-    /**
209
-     * Determine if the http method is valid.
210
-     *
211
-     * @param string $method
212
-     * @throws MethodNotSupportedException
213
-     * @return string
214
-     */
215
-
216
-    protected function parseMethod($method)
217
-    {
218
-        $method = strtolower($method);
219
-
220
-        if (strpos(self::HTTP_METHODS, $method) === false) {
221
-            throw new MethodNotSupportedException($method);
222
-        }
223
-
224
-        return $method;
225
-    }
226
-
227
-    /**
228
-     * Separate routes pattern with optional parts into n new patterns.
229
-     *
230
-     * @param string $pattern
231
-     * @return array
232
-     */
233
-
234
-    protected function parsePattern($pattern)
235
-    {
236
-        $withoutClosing = rtrim($pattern, "]");
237
-        $closingNumber  = strlen($pattern) - strlen($withoutClosing);
238
-
239
-        $segments = preg_split("~" . self::DYNAMIC_REGEX . "(*SKIP)(*F)|\[~x", $withoutClosing);
240
-        $this->parseSegments($segments, $closingNumber, $withoutClosing);
241
-
242
-        return $this->buildSegments($segments);
243
-    }
244
-
245
-    /**
246
-     * Parse all the possible patterns seeking for an incorrect or incompatible pattern.
247
-     *
248
-     * @param string[] $segments       Segments are all the possible patterns made on top of a pattern with optional segments.
249
-     * @param int      $closingNumber  The count of optional segments.
250
-     * @param string   $withoutClosing The pattern without the closing token of an optional segment. aka: ]
251
-     *
252
-     * @throws BadRouteException
253
-     */
254
-
255
-    protected function parseSegments(array $segments, $closingNumber, $withoutClosing)
256
-    {
257
-        if ($closingNumber !== count($segments) - 1) {
258
-            if (preg_match("~" . self::DYNAMIC_REGEX . "(*SKIP)(*F)|\]~x", $withoutClosing)) {
259
-                   throw new BadRouteException(BadRouteException::OPTIONAL_SEGMENTS_ON_MIDDLE);
260
-            } else throw new BadRouteException(BadRouteException::UNCLOSED_OPTIONAL_SEGMENTS);
261
-        }
262
-    }
263
-
264
-    /**
265
-     * @param string[] $segments
266
-     *
267
-     * @throws BadRouteException
268
-     * @return array
269
-     */
270
-
271
-    protected function buildSegments(array $segments)
272
-    {
273
-        $pattern  = "";
274
-        $patterns = [];
275
-        $wildcardTokens = array_keys($this->wildcards);
276
-        $wildcardRegex  = $this->wildcards;
277
-
278
-        foreach ($segments as $n => $segment) {
279
-            if ($segment === "" && $n !== 0) {
280
-                throw new BadRouteException(BadRouteException::EMPTY_OPTIONAL_PARTS);
281
-            }
282
-
283
-            $patterns[] = $pattern .= str_replace($wildcardTokens, $wildcardRegex, $segment);
284
-        }
285
-
286
-        return $patterns;
287
-    }
288
-
289
-    /**
290
-     * @param string $method
291
-     * @param string $pattern
292
-     *
293
-     * @return Route|false
294
-     */
295
-
296
-    public function findStaticRoute($method, $pattern)
297
-    {
298
-        $method = strtolower($method);
299
-        if (isset($this->statics[$method]) && isset($this->statics[$method][$pattern]))
300
-            return $this->statics[$method][$pattern];
301
-        return false;
302
-    }
303
-
304
-    /**
305
-     * @param string $method
306
-     * @param string $pattern
307
-     *
308
-     * @return array|false
309
-     */
310
-
311
-    public function findDynamicRoutes($method, $pattern)
312
-    {
313
-        $index = $this->getDynamicIndex($method, $pattern);
314
-        return isset($this->dynamics[$index]) ? $this->dynamics[$index] : false;
315
-    }
316
-
317
-    /**
318
-     * @param string $method
319
-     * @param string $pattern
320
-     *
321
-     * @return int
322
-     */
323
-
324
-    protected function getDynamicIndex($method, $pattern)
325
-    {
326
-        return crc32(strtolower($method)) + substr_count($pattern, "/");
327
-    }
328
-
329
-    /**
330
-     * @return string[]
331
-     */
332
-
333
-    public function getWildcards()
334
-    {
335
-        $wildcards = [];
336
-        foreach ($this->wildcards as $token => $regex)
337
-            $wildcards[substr($token, 1)] = substr($regex, 1);
338
-        return $wildcards;
339
-    }
340
-
341
-    /**
342
-     * @return string[]
343
-     */
344
-
345
-    public function getWildcardTokens()
346
-    {
347
-        return $this->wildcards;
348
-    }
349
-
350
-    /**
351
-     * @param string $wildcard
352
-     * @return string|null
353
-     */
354
-
355
-    public function getWildcard($wildcard)
356
-    {
357
-        return isset($this->wildcards[":$wildcard"]) ? substr($this->wildcards[":$wildcard"], 1) : null;
358
-    }
359
-
360
-    /**
361
-     * @param string $wildcard
362
-     * @param string $pattern
363
-     *
364
-     * @return self
365
-     */
366
-
367
-    public function setWildcard($wildcard, $pattern)
368
-    {
369
-        $this->wildcards[":$wildcard"] = ":$pattern";
370
-        return $this;
371
-    }
36
+	use Collectors\ControllerCollectorTrait;
37
+	use Collectors\ResourceCollectorTrait;
38
+
39
+	/**
40
+	 * These regex define the structure of a dynamic segment in a pattern.
41
+	 *
42
+	 * @var string
43
+	 */
44
+
45
+	const DYNAMIC_REGEX = "{\s*(\w*)\s*(?::\s*([^{}]*(?:{(?-1)}*)*))?\s*}";
46
+
47
+
48
+	/**
49
+	 * All the supported http methods separated by spaces.
50
+	 *
51
+	 * @var string
52
+	 */
53
+
54
+	const HTTP_METHODS = "get post put patch delete";
55
+
56
+	/**
57
+	 * The static routes are simple stored in a multidimensional array, the first
58
+	 * dimension is indexed by an http method and hold an array indexed with the patterns
59
+	 * and holding the route. ex. [METHOD => [PATTERN => ROUTE]]
60
+	 *
61
+	 * @var array
62
+	 */
63
+
64
+	protected $statics  = [];
65
+
66
+	/**
67
+	 * The dynamic routes have parameters and are stored in a hashtable that every cell have
68
+	 * an array with route patterns as indexes and routes as values. ex. [INDEX => [PATTERN => ROUTE]]
69
+	 *
70
+	 * @var array
71
+	 */
72
+
73
+	protected $dynamics = [];
74
+
75
+	/**
76
+	 * Some regex wildcards for easily definition of dynamic routes. ps. all keys and values must start with :
77
+	 *
78
+	 * @var array
79
+	 */
80
+
81
+	protected $wildcards = [
82
+		":uid"     => ":uid-[a-zA-Z0-9]",
83
+		":slug"    => ":[a-z0-9-]",
84
+		":string"  => ":\w",
85
+		":int"     => ":\d",
86
+		":integer" => ":\d",
87
+		":float"   => ":[-+]?\d*?[.]?\d",
88
+		":double"  => ":[-+]?\d*?[.]?\d",
89
+		":hex"     => ":0[xX][0-9a-fA-F]",
90
+		":octal"   => ":0[1-7][0-7]",
91
+		":bool"    => ":1|0|true|false|yes|no",
92
+		":boolean" => ":1|0|true|false|yes|no",
93
+	];
94
+
95
+	/**
96
+	 * @param string $method
97
+	 * @param string $pattern
98
+	 * @param callable $action
99
+	 *
100
+	 * @throws BadRouteException 
101
+	 * @throws MethodNotSupportedException
102
+	 *
103
+	 * @return Group
104
+	 */
105
+
106
+	public function set($method, $pattern, $action)
107
+	{
108
+		$method   = $this->parseMethod($method);
109
+		$patterns = $this->parsePattern($pattern);
110
+		$group    = new Group;
111
+
112
+		foreach ($patterns as $pattern)
113
+		{
114
+			$route = new Route($this, $method, $pattern, $action);
115
+			$group->setRoute($route);
116
+
117
+			if (strpos($pattern, "{") !== false) {
118
+				   $index = $this->getDynamicIndex($method, $pattern);
119
+				   $this->dynamics[$index][$pattern] = $route;
120
+			} else $this->statics[$method][$pattern] = $route;
121
+		}
122
+
123
+		return $group;
124
+	}
125
+
126
+	public function get   ($pattern, $action) { return $this->set("get"   , $pattern, $action); }
127
+	public function post  ($pattern, $action) { return $this->set("post"  , $pattern, $action); }
128
+	public function put   ($pattern, $action) { return $this->set("put"   , $pattern, $action); }
129
+	public function patch ($pattern, $action) { return $this->set("patch" , $pattern, $action); }
130
+	public function delete($pattern, $action) { return $this->set("delete", $pattern, $action); }
131
+
132
+	/**
133
+	 * Insert a route into several http methods.
134
+	 *
135
+	 * @param string[] $methods
136
+	 * @param string $pattern
137
+	 * @param callable $action
138
+	 *
139
+	 * @return Group
140
+	 */
141
+
142
+	public function match(array $methods, $pattern, $action)
143
+	{
144
+		$group = new Group;
145
+		foreach ($methods as $method)
146
+			$group->set($this->set($method, $pattern, $action));
147
+		return $group;
148
+	}
149
+
150
+	/**
151
+	 * Insert a route into every http method supported.
152
+	 *
153
+	 * @param string $pattern
154
+	 * @param callable $action
155
+	 *
156
+	 * @return Group
157
+	 */
158
+
159
+	public function any($pattern, $action)
160
+	{
161
+		return $this->match(explode(" ", self::HTTP_METHODS), $pattern, $action);
162
+	}
163
+
164
+	/**
165
+	 * Insert a route into every http method supported but the given ones.
166
+	 *
167
+	 * @param string $methods
168
+	 * @param string $pattern
169
+	 * @param callable $action
170
+	 *
171
+	 * @return Group
172
+	 */
173
+
174
+	public function except($methods, $pattern, $action)
175
+	{
176
+		return $this->match(array_diff(explode(" ", self::HTTP_METHODS), (array) $methods), $pattern, $action);
177
+	}
178
+
179
+	/**
180
+	 * Group all given routes.
181
+	 *
182
+	 * @param Route[] $routes
183
+	 * @return Group
184
+	 */
185
+
186
+	public function group(array $routes)
187
+	{
188
+		$group = new Group;
189
+		foreach ($routes as $route)
190
+			$group->set($route);
191
+		return $group;
192
+	}
193
+
194
+	/**
195
+	 * Remove a route from collector.
196
+	 *
197
+	 * @param string $method
198
+	 * @param string $pattern
199
+	 */
200
+
201
+	public function forget($method, $pattern)
202
+	{
203
+		if (strpos($pattern, "{") === false) {
204
+			   unset($this->statics[$method][$pattern]);
205
+		} else unset($this->dynamics[$this->getDynamicIndex($method, $pattern)][$pattern]);
206
+	}
207
+
208
+	/**
209
+	 * Determine if the http method is valid.
210
+	 *
211
+	 * @param string $method
212
+	 * @throws MethodNotSupportedException
213
+	 * @return string
214
+	 */
215
+
216
+	protected function parseMethod($method)
217
+	{
218
+		$method = strtolower($method);
219
+
220
+		if (strpos(self::HTTP_METHODS, $method) === false) {
221
+			throw new MethodNotSupportedException($method);
222
+		}
223
+
224
+		return $method;
225
+	}
226
+
227
+	/**
228
+	 * Separate routes pattern with optional parts into n new patterns.
229
+	 *
230
+	 * @param string $pattern
231
+	 * @return array
232
+	 */
233
+
234
+	protected function parsePattern($pattern)
235
+	{
236
+		$withoutClosing = rtrim($pattern, "]");
237
+		$closingNumber  = strlen($pattern) - strlen($withoutClosing);
238
+
239
+		$segments = preg_split("~" . self::DYNAMIC_REGEX . "(*SKIP)(*F)|\[~x", $withoutClosing);
240
+		$this->parseSegments($segments, $closingNumber, $withoutClosing);
241
+
242
+		return $this->buildSegments($segments);
243
+	}
244
+
245
+	/**
246
+	 * Parse all the possible patterns seeking for an incorrect or incompatible pattern.
247
+	 *
248
+	 * @param string[] $segments       Segments are all the possible patterns made on top of a pattern with optional segments.
249
+	 * @param int      $closingNumber  The count of optional segments.
250
+	 * @param string   $withoutClosing The pattern without the closing token of an optional segment. aka: ]
251
+	 *
252
+	 * @throws BadRouteException
253
+	 */
254
+
255
+	protected function parseSegments(array $segments, $closingNumber, $withoutClosing)
256
+	{
257
+		if ($closingNumber !== count($segments) - 1) {
258
+			if (preg_match("~" . self::DYNAMIC_REGEX . "(*SKIP)(*F)|\]~x", $withoutClosing)) {
259
+				   throw new BadRouteException(BadRouteException::OPTIONAL_SEGMENTS_ON_MIDDLE);
260
+			} else throw new BadRouteException(BadRouteException::UNCLOSED_OPTIONAL_SEGMENTS);
261
+		}
262
+	}
263
+
264
+	/**
265
+	 * @param string[] $segments
266
+	 *
267
+	 * @throws BadRouteException
268
+	 * @return array
269
+	 */
270
+
271
+	protected function buildSegments(array $segments)
272
+	{
273
+		$pattern  = "";
274
+		$patterns = [];
275
+		$wildcardTokens = array_keys($this->wildcards);
276
+		$wildcardRegex  = $this->wildcards;
277
+
278
+		foreach ($segments as $n => $segment) {
279
+			if ($segment === "" && $n !== 0) {
280
+				throw new BadRouteException(BadRouteException::EMPTY_OPTIONAL_PARTS);
281
+			}
282
+
283
+			$patterns[] = $pattern .= str_replace($wildcardTokens, $wildcardRegex, $segment);
284
+		}
285
+
286
+		return $patterns;
287
+	}
288
+
289
+	/**
290
+	 * @param string $method
291
+	 * @param string $pattern
292
+	 *
293
+	 * @return Route|false
294
+	 */
295
+
296
+	public function findStaticRoute($method, $pattern)
297
+	{
298
+		$method = strtolower($method);
299
+		if (isset($this->statics[$method]) && isset($this->statics[$method][$pattern]))
300
+			return $this->statics[$method][$pattern];
301
+		return false;
302
+	}
303
+
304
+	/**
305
+	 * @param string $method
306
+	 * @param string $pattern
307
+	 *
308
+	 * @return array|false
309
+	 */
310
+
311
+	public function findDynamicRoutes($method, $pattern)
312
+	{
313
+		$index = $this->getDynamicIndex($method, $pattern);
314
+		return isset($this->dynamics[$index]) ? $this->dynamics[$index] : false;
315
+	}
316
+
317
+	/**
318
+	 * @param string $method
319
+	 * @param string $pattern
320
+	 *
321
+	 * @return int
322
+	 */
323
+
324
+	protected function getDynamicIndex($method, $pattern)
325
+	{
326
+		return crc32(strtolower($method)) + substr_count($pattern, "/");
327
+	}
328
+
329
+	/**
330
+	 * @return string[]
331
+	 */
332
+
333
+	public function getWildcards()
334
+	{
335
+		$wildcards = [];
336
+		foreach ($this->wildcards as $token => $regex)
337
+			$wildcards[substr($token, 1)] = substr($regex, 1);
338
+		return $wildcards;
339
+	}
340
+
341
+	/**
342
+	 * @return string[]
343
+	 */
344
+
345
+	public function getWildcardTokens()
346
+	{
347
+		return $this->wildcards;
348
+	}
349
+
350
+	/**
351
+	 * @param string $wildcard
352
+	 * @return string|null
353
+	 */
354
+
355
+	public function getWildcard($wildcard)
356
+	{
357
+		return isset($this->wildcards[":$wildcard"]) ? substr($this->wildcards[":$wildcard"], 1) : null;
358
+	}
359
+
360
+	/**
361
+	 * @param string $wildcard
362
+	 * @param string $pattern
363
+	 *
364
+	 * @return self
365
+	 */
366
+
367
+	public function setWildcard($wildcard, $pattern)
368
+	{
369
+		$this->wildcards[":$wildcard"] = ":$pattern";
370
+		return $this;
371
+	}
372 372
     
373 373
 }
Please login to merge, or discard this patch.
src/Collectors/ResourceCollectorTrait.php 3 patches
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -22,102 +22,102 @@
 block discarded – undo
22 22
 trait ResourceCollectorTrait
23 23
 {
24 24
 
25
-    abstract public function set($method, $pattern, $action);
26
-
27
-    /**
28
-     * A map of all routes of resources.
29
-     *
30
-     * @var array
31
-     */
32
-
33
-    protected $map = [
34
-        "index"  => ["get",    "/{name}"],
35
-        "make"   => ["get",    "/{name}/make"],
36
-        "create" => ["post",   "/{name}"],
37
-        "show"   => ["get",    "/{name}/{id:int+}"],
38
-        "edit"   => ["get",    "/{name}/{id:int+}/edit"],
39
-        "update" => ["put",    "/{name}/{id:int+}"],
40
-        "delete" => ["delete", "/{name}/{id:int+}"],
41
-    ];
42
-
43
-    /**
44
-     * Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. 
45
-     * Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, 
46
-     * a resourceful route declares them in a single line of code.
47
-     *
48
-     * @param string $controller The controller name.
49
-     * @param array  $options    Some options like, "as" to name the route pattern, "only" to
50
-     *                           explicit say that only this routes will be registered, and
51
-     *                           "except" that register all the routes except the indicates.
52
-     * @return Resource
53
-     */
54
-
55
-    public function resource($controller, array $options = array())
56
-    {
57
-        $name       = isset($options["prefix"]) ? $options["prefix"] : "";
58
-        $name      .= $this->getResourceName($controller, $options);
59
-        $actions    = $this->getResourceActions($options);
60
-        $resource = new Resource;
61
-
62
-        foreach ($actions as $action => $map) {
63
-            $resource->set($this->set($map[0], $this->getResourcePath($action, $map[1], $name, $options), [$controller, $action]));
64
-        }
65
-
66
-        return $resource;
67
-    }
68
-
69
-    /**
70
-     * Collect several resources at same time.
71
-     *
72
-     * @param array $controllers Several controller names as parameters or an array with all controller names.
73
-     * @return Resource
74
-     */
75
-
76
-    public function resources(array $controllers)
77
-    {
78
-        $resource = new Resource;
79
-        foreach ($controllers as $controller)
80
-            $resource->set($this->resource($controller));
81
-        return $resource;
82
-    }
83
-
84
-    /**
85
-     * @param string $controller
86
-     * @param array $options
87
-     *
88
-     * @return mixed
89
-     */
90
-
91
-    protected function getResourceName($controller, array $options)
92
-    {
93
-        return isset($options["as"]) ? $options["as"] : str_replace("controller", "", strtolower($controller));
94
-    }
95
-
96
-    /**
97
-     * @param  array $options
98
-     * @return array
99
-     */
100
-
101
-    protected function getResourceActions(array $options)
102
-    {
103
-        return isset($options["only"])   ? array_intersect_key($this->map, array_flip((array) $options["only"])) :
104
-              (isset($options["except"]) ? array_diff_key($this->map, array_flip((array) $options["except"]))    : $this->map);
105
-    }
106
-
107
-    /**
108
-     * @param string $action
109
-     * @param string $path
110
-     * @param string $name
111
-     * @param string[] $options
112
-     *
113
-     * @return string
114
-     */
115
-
116
-    protected function getResourcePath($action, $path, $name, array $options)
117
-    {
118
-        return str_replace("{name}", $name,
119
-            $action === "make" && isset($options["translate"]["make"]) ? str_replace("make", $options["translate"]["make"], $path) :
120
-           ($action === "edit" && isset($options["translate"]["edit"]) ? str_replace("edit", $options["translate"]["edit"], $path) : $path));
121
-    }
25
+	abstract public function set($method, $pattern, $action);
26
+
27
+	/**
28
+	 * A map of all routes of resources.
29
+	 *
30
+	 * @var array
31
+	 */
32
+
33
+	protected $map = [
34
+		"index"  => ["get",    "/{name}"],
35
+		"make"   => ["get",    "/{name}/make"],
36
+		"create" => ["post",   "/{name}"],
37
+		"show"   => ["get",    "/{name}/{id:int+}"],
38
+		"edit"   => ["get",    "/{name}/{id:int+}/edit"],
39
+		"update" => ["put",    "/{name}/{id:int+}"],
40
+		"delete" => ["delete", "/{name}/{id:int+}"],
41
+	];
42
+
43
+	/**
44
+	 * Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. 
45
+	 * Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, 
46
+	 * a resourceful route declares them in a single line of code.
47
+	 *
48
+	 * @param string $controller The controller name.
49
+	 * @param array  $options    Some options like, "as" to name the route pattern, "only" to
50
+	 *                           explicit say that only this routes will be registered, and
51
+	 *                           "except" that register all the routes except the indicates.
52
+	 * @return Resource
53
+	 */
54
+
55
+	public function resource($controller, array $options = array())
56
+	{
57
+		$name       = isset($options["prefix"]) ? $options["prefix"] : "";
58
+		$name      .= $this->getResourceName($controller, $options);
59
+		$actions    = $this->getResourceActions($options);
60
+		$resource = new Resource;
61
+
62
+		foreach ($actions as $action => $map) {
63
+			$resource->set($this->set($map[0], $this->getResourcePath($action, $map[1], $name, $options), [$controller, $action]));
64
+		}
65
+
66
+		return $resource;
67
+	}
68
+
69
+	/**
70
+	 * Collect several resources at same time.
71
+	 *
72
+	 * @param array $controllers Several controller names as parameters or an array with all controller names.
73
+	 * @return Resource
74
+	 */
75
+
76
+	public function resources(array $controllers)
77
+	{
78
+		$resource = new Resource;
79
+		foreach ($controllers as $controller)
80
+			$resource->set($this->resource($controller));
81
+		return $resource;
82
+	}
83
+
84
+	/**
85
+	 * @param string $controller
86
+	 * @param array $options
87
+	 *
88
+	 * @return mixed
89
+	 */
90
+
91
+	protected function getResourceName($controller, array $options)
92
+	{
93
+		return isset($options["as"]) ? $options["as"] : str_replace("controller", "", strtolower($controller));
94
+	}
95
+
96
+	/**
97
+	 * @param  array $options
98
+	 * @return array
99
+	 */
100
+
101
+	protected function getResourceActions(array $options)
102
+	{
103
+		return isset($options["only"])   ? array_intersect_key($this->map, array_flip((array) $options["only"])) :
104
+			  (isset($options["except"]) ? array_diff_key($this->map, array_flip((array) $options["except"]))    : $this->map);
105
+	}
106
+
107
+	/**
108
+	 * @param string $action
109
+	 * @param string $path
110
+	 * @param string $name
111
+	 * @param string[] $options
112
+	 *
113
+	 * @return string
114
+	 */
115
+
116
+	protected function getResourcePath($action, $path, $name, array $options)
117
+	{
118
+		return str_replace("{name}", $name,
119
+			$action === "make" && isset($options["translate"]["make"]) ? str_replace("make", $options["translate"]["make"], $path) :
120
+		   ($action === "edit" && isset($options["translate"]["edit"]) ? str_replace("edit", $options["translate"]["edit"], $path) : $path));
121
+	}
122 122
 
123 123
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -10 removed lines patch added patch discarded remove patch
@@ -31,12 +31,12 @@  discard block
 block discarded – undo
31 31
      */
32 32
 
33 33
     protected $map = [
34
-        "index"  => ["get",    "/{name}"],
35
-        "make"   => ["get",    "/{name}/make"],
36
-        "create" => ["post",   "/{name}"],
37
-        "show"   => ["get",    "/{name}/{id:int+}"],
38
-        "edit"   => ["get",    "/{name}/{id:int+}/edit"],
39
-        "update" => ["put",    "/{name}/{id:int+}"],
34
+        "index"  => ["get", "/{name}"],
35
+        "make"   => ["get", "/{name}/make"],
36
+        "create" => ["post", "/{name}"],
37
+        "show"   => ["get", "/{name}/{id:int+}"],
38
+        "edit"   => ["get", "/{name}/{id:int+}/edit"],
39
+        "update" => ["put", "/{name}/{id:int+}"],
40 40
         "delete" => ["delete", "/{name}/{id:int+}"],
41 41
     ];
42 42
 
@@ -100,8 +100,7 @@  discard block
 block discarded – undo
100 100
 
101 101
     protected function getResourceActions(array $options)
102 102
     {
103
-        return isset($options["only"])   ? array_intersect_key($this->map, array_flip((array) $options["only"])) :
104
-              (isset($options["except"]) ? array_diff_key($this->map, array_flip((array) $options["except"]))    : $this->map);
103
+        return isset($options["only"]) ? array_intersect_key($this->map, array_flip((array) $options["only"])) : (isset($options["except"]) ? array_diff_key($this->map, array_flip((array) $options["except"])) : $this->map);
105 104
     }
106 105
 
107 106
     /**
@@ -116,8 +115,7 @@  discard block
 block discarded – undo
116 115
     protected function getResourcePath($action, $path, $name, array $options)
117 116
     {
118 117
         return str_replace("{name}", $name,
119
-            $action === "make" && isset($options["translate"]["make"]) ? str_replace("make", $options["translate"]["make"], $path) :
120
-           ($action === "edit" && isset($options["translate"]["edit"]) ? str_replace("edit", $options["translate"]["edit"], $path) : $path));
118
+            $action === "make" && isset($options["translate"]["make"]) ? str_replace("make", $options["translate"]["make"], $path) : ($action === "edit" && isset($options["translate"]["edit"]) ? str_replace("edit", $options["translate"]["edit"], $path) : $path));
121 119
     }
122 120
 
123 121
 }
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -76,8 +76,9 @@
 block discarded – undo
76 76
     public function resources(array $controllers)
77 77
     {
78 78
         $resource = new Resource;
79
-        foreach ($controllers as $controller)
80
-            $resource->set($this->resource($controller));
79
+        foreach ($controllers as $controller) {
80
+                    $resource->set($this->resource($controller));
81
+        }
81 82
         return $resource;
82 83
     }
83 84
 
Please login to merge, or discard this patch.
src/Matcher.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 
236 236
     protected function checkStaticRouteInOtherMethods($targetHttpMethod, $path)
237 237
     {
238
-        return array_filter($this->getHttpMethodsBut($targetHttpMethod), function ($httpMethod) use ($path) {
238
+        return array_filter($this->getHttpMethodsBut($targetHttpMethod), function($httpMethod) use ($path) {
239 239
             return (bool) $this->collector->findStaticRoute($httpMethod, $path);
240 240
         });
241 241
     }
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 
252 252
     protected function checkDynamicRouteInOtherMethods($targetHttpMethod, $path)
253 253
     {
254
-        return array_filter($this->getHttpMethodsBut($targetHttpMethod), function ($httpMethod) use ($path) {
254
+        return array_filter($this->getHttpMethodsBut($targetHttpMethod), function($httpMethod) use ($path) {
255 255
             return (bool) $this->matchDynamicRoute($httpMethod, $path);
256 256
         });
257 257
     }
Please login to merge, or discard this patch.
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -23,271 +23,271 @@
 block discarded – undo
23 23
 class Matcher
24 24
 {
25 25
 
26
-    /**
27
-     * @var Collector
28
-     */
29
-
30
-    protected $collector;
31
-
32
-    /**
33
-     * Define a basepath to all routes.
34
-     *
35
-     * @var string
36
-     */
37
-
38
-    protected $basepath = "";
39
-
40
-    /**
41
-     * Construct the route dispatcher.
42
-     *
43
-     * @param Collector $collector
44
-     * @param string $basepath Define a Path prefix that must be excluded on matches.
45
-     */
46
-
47
-    public function __construct(Collector $collector, $basepath = "")
48
-    {
49
-        $this->collector = $collector;
50
-        $this->basepath  = $basepath;
51
-    }
52
-
53
-    /**
54
-     * Find a route that matches the given arguments.
55
-     * 
56
-     * @param string $httpMethod
57
-     * @param string $path
58
-     *
59
-     * @throws NotFoundException
60
-     * @throws MethodNotAllowedException
61
-     *
62
-     * @return Route
63
-     */
64
-
65
-    public function match($httpMethod, $path)
66
-    {
67
-        $path = $this->parsePath($path);
68
-
69
-        if ($route = $this->collector->findStaticRoute($httpMethod, $path)) {
70
-            return $route;
71
-        }
72
-
73
-        if ($route = $this->matchDynamicRoute($httpMethod, $path)) {
74
-            return $route;
75
-        }
76
-
77
-        $this->matchSimilarRoute($httpMethod, $path);
78
-    }
79
-
80
-    /**
81
-     * Find and return the request dynamic route based on the compiled data and Path.
82
-     *
83
-     * @param string $httpMethod
84
-     * @param string $path
85
-     *
86
-     * @return Route|false If the request match an array with the action and parameters will
87
-     *                     be returned otherwise a false will.
88
-     */
89
-
90
-    protected function matchDynamicRoute($httpMethod, $path)
91
-    {
92
-        if ($routes = $this->collector->findDynamicRoutes($httpMethod, $path)) {
93
-            // chunk routes for smaller regex groups using the Sturges' Formula
94
-            foreach (array_chunk($routes, round(1 + 3.3 * log(count($routes))), true) as $chunk) {
95
-                array_map([$this, "buildRoute"], $chunk);
96
-                list($pattern, $map) = $this->buildGroup($chunk);
97
-
98
-                if (!preg_match($pattern, $path, $matches)) {
99
-                    continue;
100
-                }
101
-
102
-                /** @var Route $route */
103
-                $route = $map[count($matches)];
104
-                unset($matches[0]);
105
-
106
-                $route->setParams(array_combine($route->getParams(), array_filter($matches)));
107
-                $route->setMatcher($this);
108
-
109
-                return $route;
110
-            }
111
-        }
112
-
113
-        return false;
114
-    }
115
-
116
-    /**
117
-     * Parse the dynamic segments of the pattern and replace then for
118
-     * corresponding regex.
119
-     *
120
-     * @param Route $route
121
-     * @return Route
122
-     */
123
-
124
-    protected function buildRoute(Route $route)
125
-    {
126
-        if ($route->getBlock()) {
127
-            return $route;
128
-        }
129
-
130
-        list($pattern, $params) = $this->parsePlaceholders($route->getPattern());
131
-        return $route->setPatternWithoutReset($pattern)->setParams($params)->setBlock(true);
132
-    }
133
-
134
-    /**
135
-     * Group several dynamic routes patterns into one big regex and maps
136
-     * the routes to the pattern positions in the big regex.
137
-     *
138
-     * @param Route[] $routes
139
-     * @return array
140
-     */
141
-
142
-    protected function buildGroup(array $routes)
143
-    {
144
-        $groupCount = (int) $map = $regex = [];
145
-
146
-        foreach ($routes as $route) {
147
-            $params           = $route->getParams();
148
-            $paramsCount      = count($params);
149
-            $groupCount       = max($groupCount, $paramsCount) + 1;
150
-            $regex[]          = $route->getPattern() . str_repeat("()", $groupCount - $paramsCount - 1);
151
-            $map[$groupCount] = $route;
152
-        }
153
-
154
-        return ["~^(?|" . implode("|", $regex) . ")$~", $map];
155
-    }
156
-
157
-    /**
158
-     * Parse an route pattern seeking for parameters and build the route regex.
159
-     *
160
-     * @param string $pattern
161
-     * @return array 0 => new route regex, 1 => map of parameter names
162
-     */
163
-
164
-    protected function parsePlaceholders($pattern)
165
-    {
166
-        $params = [];
167
-        preg_match_all("~" . Collector::DYNAMIC_REGEX . "~x", $pattern, $matches, PREG_SET_ORDER);
168
-
169
-        foreach ((array) $matches as $key => $match) {
170
-            $pattern = str_replace($match[0], isset($match[2]) ? "({$match[2]})" : "([^/]+)", $pattern);
171
-            $params[$key] = $match[1];
172
-        }
173
-
174
-        return [$pattern, $params];
175
-    }
176
-
177
-    /**
178
-     * Get only the path of a given url.
179
-     *
180
-     * @param string $path The given URL
181
-     *
182
-     * @throws Exception
183
-     * @return string
184
-     */
185
-
186
-    protected function parsePath($path)
187
-    {
188
-        $path = parse_url(substr(strstr(";" . $path, ";" . $this->basepath), strlen(";" . $this->basepath)), PHP_URL_PATH);
189
-
190
-        if ($path === false) {
191
-            throw new Exception("Seriously malformed URL passed to route matcher.");
192
-        }
193
-
194
-        return $path;
195
-    }
196
-
197
-    /**
198
-     * Generate an HTTP error request with method not allowed or not found.
199
-     *
200
-     * @param string $httpMethod
201
-     * @param string $path
202
-     *
203
-     * @throws NotFoundException
204
-     * @throws MethodNotAllowedException
205
-     */
206
-
207
-    protected function matchSimilarRoute($httpMethod, $path)
208
-    {
209
-        $dm = [];
210
-
211
-        if (($sm = $this->checkStaticRouteInOtherMethods($httpMethod, $path))
212
-                || ($dm = $this->checkDynamicRouteInOtherMethods($httpMethod, $path))) {
213
-            throw new MethodNotAllowedException($httpMethod, $path, array_merge((array) $sm, (array) $dm));
214
-        }
215
-
216
-        throw new NotFoundException;
217
-    }
218
-
219
-    /**
220
-     * Verify if a static route match in another method than the requested.
221
-     *
222
-     * @param string $targetHttpMethod The HTTP method that must not be checked
223
-     * @param string $path              The Path that must be matched.
224
-     *
225
-     * @return array
226
-     */
227
-
228
-    protected function checkStaticRouteInOtherMethods($targetHttpMethod, $path)
229
-    {
230
-        return array_filter($this->getHttpMethodsBut($targetHttpMethod), function ($httpMethod) use ($path) {
231
-            return (bool) $this->collector->findStaticRoute($httpMethod, $path);
232
-        });
233
-    }
234
-
235
-    /**
236
-     * Verify if a dynamic route match in another method than the requested.
237
-     *
238
-     * @param string $targetHttpMethod The HTTP method that must not be checked
239
-     * @param string $path             The Path that must be matched.
240
-     *
241
-     * @return array
242
-     */
243
-
244
-    protected function checkDynamicRouteInOtherMethods($targetHttpMethod, $path)
245
-    {
246
-        return array_filter($this->getHttpMethodsBut($targetHttpMethod), function ($httpMethod) use ($path) {
247
-            return (bool) $this->matchDynamicRoute($httpMethod, $path);
248
-        });
249
-    }
250
-
251
-    /**
252
-     * Strip the given http methods and return all the others.
253
-     *
254
-     * @param string|string[]
255
-     * @return array
256
-     */
257
-
258
-    protected function getHttpMethodsBut($targetHttpMethod)
259
-    {
260
-        return array_diff(explode(" ", Collector::HTTP_METHODS), (array) $targetHttpMethod);
261
-    }
262
-
263
-    /**
264
-     * @return Collector
265
-     */
266
-
267
-    public function getCollector()
268
-    {
269
-        return $this->collector;
270
-    }
271
-
272
-    /**
273
-     * @return string
274
-     */
275
-
276
-    public function getBasePath()
277
-    {
278
-        return $this->basepath;
279
-    }
280
-
281
-    /**
282
-     * Set a new basepath, this will be a prefix that must be excluded in
283
-     * every requested Path.
284
-     *
285
-     * @param string $basepath The new basepath
286
-     */
26
+	/**
27
+	 * @var Collector
28
+	 */
29
+
30
+	protected $collector;
31
+
32
+	/**
33
+	 * Define a basepath to all routes.
34
+	 *
35
+	 * @var string
36
+	 */
37
+
38
+	protected $basepath = "";
39
+
40
+	/**
41
+	 * Construct the route dispatcher.
42
+	 *
43
+	 * @param Collector $collector
44
+	 * @param string $basepath Define a Path prefix that must be excluded on matches.
45
+	 */
46
+
47
+	public function __construct(Collector $collector, $basepath = "")
48
+	{
49
+		$this->collector = $collector;
50
+		$this->basepath  = $basepath;
51
+	}
52
+
53
+	/**
54
+	 * Find a route that matches the given arguments.
55
+	 * 
56
+	 * @param string $httpMethod
57
+	 * @param string $path
58
+	 *
59
+	 * @throws NotFoundException
60
+	 * @throws MethodNotAllowedException
61
+	 *
62
+	 * @return Route
63
+	 */
64
+
65
+	public function match($httpMethod, $path)
66
+	{
67
+		$path = $this->parsePath($path);
68
+
69
+		if ($route = $this->collector->findStaticRoute($httpMethod, $path)) {
70
+			return $route;
71
+		}
72
+
73
+		if ($route = $this->matchDynamicRoute($httpMethod, $path)) {
74
+			return $route;
75
+		}
76
+
77
+		$this->matchSimilarRoute($httpMethod, $path);
78
+	}
79
+
80
+	/**
81
+	 * Find and return the request dynamic route based on the compiled data and Path.
82
+	 *
83
+	 * @param string $httpMethod
84
+	 * @param string $path
85
+	 *
86
+	 * @return Route|false If the request match an array with the action and parameters will
87
+	 *                     be returned otherwise a false will.
88
+	 */
89
+
90
+	protected function matchDynamicRoute($httpMethod, $path)
91
+	{
92
+		if ($routes = $this->collector->findDynamicRoutes($httpMethod, $path)) {
93
+			// chunk routes for smaller regex groups using the Sturges' Formula
94
+			foreach (array_chunk($routes, round(1 + 3.3 * log(count($routes))), true) as $chunk) {
95
+				array_map([$this, "buildRoute"], $chunk);
96
+				list($pattern, $map) = $this->buildGroup($chunk);
97
+
98
+				if (!preg_match($pattern, $path, $matches)) {
99
+					continue;
100
+				}
101
+
102
+				/** @var Route $route */
103
+				$route = $map[count($matches)];
104
+				unset($matches[0]);
105
+
106
+				$route->setParams(array_combine($route->getParams(), array_filter($matches)));
107
+				$route->setMatcher($this);
108
+
109
+				return $route;
110
+			}
111
+		}
112
+
113
+		return false;
114
+	}
115
+
116
+	/**
117
+	 * Parse the dynamic segments of the pattern and replace then for
118
+	 * corresponding regex.
119
+	 *
120
+	 * @param Route $route
121
+	 * @return Route
122
+	 */
123
+
124
+	protected function buildRoute(Route $route)
125
+	{
126
+		if ($route->getBlock()) {
127
+			return $route;
128
+		}
129
+
130
+		list($pattern, $params) = $this->parsePlaceholders($route->getPattern());
131
+		return $route->setPatternWithoutReset($pattern)->setParams($params)->setBlock(true);
132
+	}
133
+
134
+	/**
135
+	 * Group several dynamic routes patterns into one big regex and maps
136
+	 * the routes to the pattern positions in the big regex.
137
+	 *
138
+	 * @param Route[] $routes
139
+	 * @return array
140
+	 */
141
+
142
+	protected function buildGroup(array $routes)
143
+	{
144
+		$groupCount = (int) $map = $regex = [];
145
+
146
+		foreach ($routes as $route) {
147
+			$params           = $route->getParams();
148
+			$paramsCount      = count($params);
149
+			$groupCount       = max($groupCount, $paramsCount) + 1;
150
+			$regex[]          = $route->getPattern() . str_repeat("()", $groupCount - $paramsCount - 1);
151
+			$map[$groupCount] = $route;
152
+		}
153
+
154
+		return ["~^(?|" . implode("|", $regex) . ")$~", $map];
155
+	}
156
+
157
+	/**
158
+	 * Parse an route pattern seeking for parameters and build the route regex.
159
+	 *
160
+	 * @param string $pattern
161
+	 * @return array 0 => new route regex, 1 => map of parameter names
162
+	 */
163
+
164
+	protected function parsePlaceholders($pattern)
165
+	{
166
+		$params = [];
167
+		preg_match_all("~" . Collector::DYNAMIC_REGEX . "~x", $pattern, $matches, PREG_SET_ORDER);
168
+
169
+		foreach ((array) $matches as $key => $match) {
170
+			$pattern = str_replace($match[0], isset($match[2]) ? "({$match[2]})" : "([^/]+)", $pattern);
171
+			$params[$key] = $match[1];
172
+		}
173
+
174
+		return [$pattern, $params];
175
+	}
176
+
177
+	/**
178
+	 * Get only the path of a given url.
179
+	 *
180
+	 * @param string $path The given URL
181
+	 *
182
+	 * @throws Exception
183
+	 * @return string
184
+	 */
185
+
186
+	protected function parsePath($path)
187
+	{
188
+		$path = parse_url(substr(strstr(";" . $path, ";" . $this->basepath), strlen(";" . $this->basepath)), PHP_URL_PATH);
189
+
190
+		if ($path === false) {
191
+			throw new Exception("Seriously malformed URL passed to route matcher.");
192
+		}
193
+
194
+		return $path;
195
+	}
196
+
197
+	/**
198
+	 * Generate an HTTP error request with method not allowed or not found.
199
+	 *
200
+	 * @param string $httpMethod
201
+	 * @param string $path
202
+	 *
203
+	 * @throws NotFoundException
204
+	 * @throws MethodNotAllowedException
205
+	 */
206
+
207
+	protected function matchSimilarRoute($httpMethod, $path)
208
+	{
209
+		$dm = [];
210
+
211
+		if (($sm = $this->checkStaticRouteInOtherMethods($httpMethod, $path))
212
+				|| ($dm = $this->checkDynamicRouteInOtherMethods($httpMethod, $path))) {
213
+			throw new MethodNotAllowedException($httpMethod, $path, array_merge((array) $sm, (array) $dm));
214
+		}
215
+
216
+		throw new NotFoundException;
217
+	}
218
+
219
+	/**
220
+	 * Verify if a static route match in another method than the requested.
221
+	 *
222
+	 * @param string $targetHttpMethod The HTTP method that must not be checked
223
+	 * @param string $path              The Path that must be matched.
224
+	 *
225
+	 * @return array
226
+	 */
227
+
228
+	protected function checkStaticRouteInOtherMethods($targetHttpMethod, $path)
229
+	{
230
+		return array_filter($this->getHttpMethodsBut($targetHttpMethod), function ($httpMethod) use ($path) {
231
+			return (bool) $this->collector->findStaticRoute($httpMethod, $path);
232
+		});
233
+	}
234
+
235
+	/**
236
+	 * Verify if a dynamic route match in another method than the requested.
237
+	 *
238
+	 * @param string $targetHttpMethod The HTTP method that must not be checked
239
+	 * @param string $path             The Path that must be matched.
240
+	 *
241
+	 * @return array
242
+	 */
243
+
244
+	protected function checkDynamicRouteInOtherMethods($targetHttpMethod, $path)
245
+	{
246
+		return array_filter($this->getHttpMethodsBut($targetHttpMethod), function ($httpMethod) use ($path) {
247
+			return (bool) $this->matchDynamicRoute($httpMethod, $path);
248
+		});
249
+	}
250
+
251
+	/**
252
+	 * Strip the given http methods and return all the others.
253
+	 *
254
+	 * @param string|string[]
255
+	 * @return array
256
+	 */
257
+
258
+	protected function getHttpMethodsBut($targetHttpMethod)
259
+	{
260
+		return array_diff(explode(" ", Collector::HTTP_METHODS), (array) $targetHttpMethod);
261
+	}
262
+
263
+	/**
264
+	 * @return Collector
265
+	 */
266
+
267
+	public function getCollector()
268
+	{
269
+		return $this->collector;
270
+	}
271
+
272
+	/**
273
+	 * @return string
274
+	 */
275
+
276
+	public function getBasePath()
277
+	{
278
+		return $this->basepath;
279
+	}
280
+
281
+	/**
282
+	 * Set a new basepath, this will be a prefix that must be excluded in
283
+	 * every requested Path.
284
+	 *
285
+	 * @param string $basepath The new basepath
286
+	 */
287 287
     
288
-    public function setBasePath($basepath)
289
-    {
290
-        $this->basepath = $basepath;
291
-    }
288
+	public function setBasePath($basepath)
289
+	{
290
+		$this->basepath = $basepath;
291
+	}
292 292
 
293 293
 }
Please login to merge, or discard this patch.
src/Resource.php 2 patches
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -173,7 +173,9 @@
 block discarded – undo
173 173
         foreach ($segments as $index => $segment) {
174 174
             if (strpos($segment, "{") === 0) {
175 175
                    $pattern .= "/{" . $segments[$index - 1] . "_" . ltrim($segment, "{");
176
-            } else $pattern .= $segment;
176
+            } else {
177
+            	$pattern .= $segment;
178
+            }
177 179
         }
178 180
 
179 181
         return $pattern;
Please login to merge, or discard this patch.
Indentation   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -20,160 +20,160 @@
 block discarded – undo
20 20
 class Resource extends Group
21 21
 {
22 22
 
23
-    /**
24
-     * @inheritdoc
25
-     * @throws \BadMethodCallException
26
-     */
27
-
28
-    public function setMethod($method)
29
-    {
30
-        throw new \BadMethodCallException("Resources can't chance they http method.");
31
-    }
32
-
33
-    /**
34
-     * Remove the routes without the passed methods.
35
-     *
36
-     * @param string|string[] $methods
37
-     * @return self
38
-     */
39
-
40
-    public function only($methods)
41
-    {
42
-        $this->filterByMethod((array) $methods, false);
43
-        return $this;
44
-    }
45
-
46
-    /**
47
-     * Remove the routes with the passed methods.
48
-     *
49
-     * @param string|string[] $methods
50
-     * @return self
51
-     */
52
-
53
-    public function except($methods)
54
-    {
55
-        $this->filterByMethod((array) $methods, true);
56
-        return $this;
57
-    }
58
-
59
-    /**
60
-     * Forget the grouped routes filtering by http methods.
61
-     *
62
-     * @param string[] $methods
63
-     * @param bool $alt Should remove?
64
-     */
65
-
66
-    private function filterByMethod(array $methods, $alt)
67
-    {
68
-        $methods = array_flip(array_map('strtolower', $methods));
69
-
70
-        foreach ($this->routes as $route) {
71
-            if (isset($methods[$route->getAction()[1]]) === $alt) {
72
-                $route->forget();
73
-            }
74
-        }
75
-    }
76
-
77
-    /**
78
-     * Translate the "make" or "edit" from resources path.
79
-     *
80
-     * @param string[] $translations
81
-     * @return self
82
-     */
83
-
84
-    public function translate(array $translations)
85
-    {
86
-        foreach ($this->routes as $route) {
87
-            $action = $route->getAction()[1];
88
-
89
-            if ($action === "make" && isset($translations["make"])) {
90
-                $route->setPatternWithoutReset(str_replace("make", $translations["make"], $route->getPattern()));
91
-            } elseif ($action === "edit" && isset($translations["edit"])) {
92
-                $route->setPatternWithoutReset(str_replace("edit", $translations["edit"], $route->getPattern()));
93
-            }
94
-        }
95
-
96
-        return $this;
97
-    }
98
-
99
-    /**
100
-     * Add a route or a group of routes to the resource, it means that
101
-     * every added route will now receive the parameters of the resource, like id.
102
-     *
103
-     * @param Route|Group $route
104
-     * @return self
105
-     */
106
-
107
-    public function member($route)
108
-    {
109
-        $resource = new Resource;
110
-        $resource->set($route);
111
-        $this->nest($resource);
112
-    }
113
-
114
-    /**
115
-     * Nested routes capture the relation between a resource and another resource.
116
-     *
117
-     * @param Resource $resource
118
-     * @return self
119
-     */
120
-
121
-    public function nest(Resource $resource)
122
-    {
123
-        /** @var self $resource */
124
-        foreach ($this->routes as $route) {
125
-            if ($route->getAction()[1] === "show") {
126
-                $this->set($resource->forget()->setPrefix($this->getNestedPrefix($route->getPattern()))); break;
127
-            }
128
-        }
129
-
130
-        return $this;
131
-    }
132
-
133
-    /**
134
-     * Nest resources but with only build routes with the minimal amount of information
135
-     * to uniquely identify the resource.
136
-     *
137
-     * @param Resource $resource
138
-     * @return self
139
-     */
140
-
141
-    public function shallow(Resource $resource)
142
-    {
143
-        /** @var self $resource */
144
-        $newResource = new Resource;
145
-        $resource->forget();
146
-        $routes = $resource->all();
147
-
148
-        foreach ($routes as $route) {
149
-            if (strpos("index make create", $route->getAction()[1]) !== false) {
150
-                $newResource->set($route);
151
-            }
152
-        }
153
-
154
-        return $this->nest($newResource);
155
-    }
156
-
157
-    /**
158
-     * Resolve the nesting pattern, setting the prefixes based on
159
-     * parent resources patterns.
160
-     *
161
-     * @param string $pattern
162
-     * @return string
163
-     */
164
-
165
-    protected function getNestedPrefix($pattern)
166
-    {
167
-        $segments = explode("/", $pattern);
168
-        $pattern = "";
169
-
170
-        foreach ($segments as $index => $segment) {
171
-            if (strpos($segment, "{") === 0) {
172
-                   $pattern .= "/{" . $segments[$index - 1] . "_" . ltrim($segment, "{");
173
-            } else $pattern .= $segment;
174
-        }
175
-
176
-        return $pattern;
177
-    }
23
+	/**
24
+	 * @inheritdoc
25
+	 * @throws \BadMethodCallException
26
+	 */
27
+
28
+	public function setMethod($method)
29
+	{
30
+		throw new \BadMethodCallException("Resources can't chance they http method.");
31
+	}
32
+
33
+	/**
34
+	 * Remove the routes without the passed methods.
35
+	 *
36
+	 * @param string|string[] $methods
37
+	 * @return self
38
+	 */
39
+
40
+	public function only($methods)
41
+	{
42
+		$this->filterByMethod((array) $methods, false);
43
+		return $this;
44
+	}
45
+
46
+	/**
47
+	 * Remove the routes with the passed methods.
48
+	 *
49
+	 * @param string|string[] $methods
50
+	 * @return self
51
+	 */
52
+
53
+	public function except($methods)
54
+	{
55
+		$this->filterByMethod((array) $methods, true);
56
+		return $this;
57
+	}
58
+
59
+	/**
60
+	 * Forget the grouped routes filtering by http methods.
61
+	 *
62
+	 * @param string[] $methods
63
+	 * @param bool $alt Should remove?
64
+	 */
65
+
66
+	private function filterByMethod(array $methods, $alt)
67
+	{
68
+		$methods = array_flip(array_map('strtolower', $methods));
69
+
70
+		foreach ($this->routes as $route) {
71
+			if (isset($methods[$route->getAction()[1]]) === $alt) {
72
+				$route->forget();
73
+			}
74
+		}
75
+	}
76
+
77
+	/**
78
+	 * Translate the "make" or "edit" from resources path.
79
+	 *
80
+	 * @param string[] $translations
81
+	 * @return self
82
+	 */
83
+
84
+	public function translate(array $translations)
85
+	{
86
+		foreach ($this->routes as $route) {
87
+			$action = $route->getAction()[1];
88
+
89
+			if ($action === "make" && isset($translations["make"])) {
90
+				$route->setPatternWithoutReset(str_replace("make", $translations["make"], $route->getPattern()));
91
+			} elseif ($action === "edit" && isset($translations["edit"])) {
92
+				$route->setPatternWithoutReset(str_replace("edit", $translations["edit"], $route->getPattern()));
93
+			}
94
+		}
95
+
96
+		return $this;
97
+	}
98
+
99
+	/**
100
+	 * Add a route or a group of routes to the resource, it means that
101
+	 * every added route will now receive the parameters of the resource, like id.
102
+	 *
103
+	 * @param Route|Group $route
104
+	 * @return self
105
+	 */
106
+
107
+	public function member($route)
108
+	{
109
+		$resource = new Resource;
110
+		$resource->set($route);
111
+		$this->nest($resource);
112
+	}
113
+
114
+	/**
115
+	 * Nested routes capture the relation between a resource and another resource.
116
+	 *
117
+	 * @param Resource $resource
118
+	 * @return self
119
+	 */
120
+
121
+	public function nest(Resource $resource)
122
+	{
123
+		/** @var self $resource */
124
+		foreach ($this->routes as $route) {
125
+			if ($route->getAction()[1] === "show") {
126
+				$this->set($resource->forget()->setPrefix($this->getNestedPrefix($route->getPattern()))); break;
127
+			}
128
+		}
129
+
130
+		return $this;
131
+	}
132
+
133
+	/**
134
+	 * Nest resources but with only build routes with the minimal amount of information
135
+	 * to uniquely identify the resource.
136
+	 *
137
+	 * @param Resource $resource
138
+	 * @return self
139
+	 */
140
+
141
+	public function shallow(Resource $resource)
142
+	{
143
+		/** @var self $resource */
144
+		$newResource = new Resource;
145
+		$resource->forget();
146
+		$routes = $resource->all();
147
+
148
+		foreach ($routes as $route) {
149
+			if (strpos("index make create", $route->getAction()[1]) !== false) {
150
+				$newResource->set($route);
151
+			}
152
+		}
153
+
154
+		return $this->nest($newResource);
155
+	}
156
+
157
+	/**
158
+	 * Resolve the nesting pattern, setting the prefixes based on
159
+	 * parent resources patterns.
160
+	 *
161
+	 * @param string $pattern
162
+	 * @return string
163
+	 */
164
+
165
+	protected function getNestedPrefix($pattern)
166
+	{
167
+		$segments = explode("/", $pattern);
168
+		$pattern = "";
169
+
170
+		foreach ($segments as $index => $segment) {
171
+			if (strpos($segment, "{") === 0) {
172
+				   $pattern .= "/{" . $segments[$index - 1] . "_" . ltrim($segment, "{");
173
+			} else $pattern .= $segment;
174
+		}
175
+
176
+		return $pattern;
177
+	}
178 178
 
179 179
 }
Please login to merge, or discard this patch.
src/Strategies/EnhancerAbstractStrategy.php 2 patches
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -24,37 +24,37 @@
 block discarded – undo
24 24
 abstract class EnhancerAbstractStrategy implements StrategyInterface
25 25
 {
26 26
 
27
-    /**
28
-     * Key used to store the real route strategy on metadata.
29
-     *
30
-     * @var string
31
-     */
32
-
33
-    protected $metadataStrategyKey = "strategy";
34
-
35
-    /**
36
-     * @inheritdoc
37
-     * @throws BadRouteException
38
-     */
39
-
40
-    public function call(Route $route)
41
-    {
42
-        if ($route->hasMetadata($this->metadataStrategyKey)) {
43
-               $route->setStrategy($route->getMetadata($this->metadataStrategyKey));
44
-        } else $route->setStrategy(null);
45
-
46
-        $this->enhance($route);
47
-
48
-        return $route->call();
49
-    }
50
-
51
-    /**
52
-     * Manipulate route object before the dispatch.
53
-     *
54
-     * @param Route $route
55
-     * @return mixed
56
-     */
57
-
58
-    abstract public function enhance(Route $route);
27
+	/**
28
+	 * Key used to store the real route strategy on metadata.
29
+	 *
30
+	 * @var string
31
+	 */
32
+
33
+	protected $metadataStrategyKey = "strategy";
34
+
35
+	/**
36
+	 * @inheritdoc
37
+	 * @throws BadRouteException
38
+	 */
39
+
40
+	public function call(Route $route)
41
+	{
42
+		if ($route->hasMetadata($this->metadataStrategyKey)) {
43
+			   $route->setStrategy($route->getMetadata($this->metadataStrategyKey));
44
+		} else $route->setStrategy(null);
45
+
46
+		$this->enhance($route);
47
+
48
+		return $route->call();
49
+	}
50
+
51
+	/**
52
+	 * Manipulate route object before the dispatch.
53
+	 *
54
+	 * @param Route $route
55
+	 * @return mixed
56
+	 */
57
+
58
+	abstract public function enhance(Route $route);
59 59
 
60 60
 }
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -41,7 +41,9 @@
 block discarded – undo
41 41
     {
42 42
         if ($route->hasMetadata($this->metadataStrategyKey)) {
43 43
                $route->setStrategy($route->getMetadata($this->metadataStrategyKey));
44
-        } else $route->setStrategy(null);
44
+        } else {
45
+        	$route->setStrategy(null);
46
+        }
45 47
 
46 48
         $this->enhance($route);
47 49
 
Please login to merge, or discard this patch.
src/Strategies/MatcherAwareInterface.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -20,16 +20,16 @@
 block discarded – undo
20 20
 interface MatcherAwareInterface
21 21
 {
22 22
 
23
-    /**
24
-     * @param \Codeburner\Router\Matcher $matcher
25
-     */
23
+	/**
24
+	 * @param \Codeburner\Router\Matcher $matcher
25
+	 */
26 26
 
27
-    public function setMatcher(\Codeburner\Router\Matcher $matcher);
27
+	public function setMatcher(\Codeburner\Router\Matcher $matcher);
28 28
 
29
-    /**
30
-     * @return \Codeburner\Router\Matcher
31
-     */
29
+	/**
30
+	 * @return \Codeburner\Router\Matcher
31
+	 */
32 32
 
33
-    public function getMatcher();
33
+	public function getMatcher();
34 34
 
35 35
 }
36 36
\ No newline at end of file
Please login to merge, or discard this patch.
src/Strategies/StrategyInterface.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -19,13 +19,13 @@
 block discarded – undo
19 19
 interface StrategyInterface
20 20
 {
21 21
 
22
-    /**
23
-     * Dispatch the matched route action.
24
-     *
25
-     * @param \Codeburner\Router\Route $route
26
-     * @return mixed The response of request.
27
-     */
22
+	/**
23
+	 * Dispatch the matched route action.
24
+	 *
25
+	 * @param \Codeburner\Router\Route $route
26
+	 * @return mixed The response of request.
27
+	 */
28 28
 
29
-    public function call(\Codeburner\Router\Route $route);
29
+	public function call(\Codeburner\Router\Route $route);
30 30
 
31 31
 }
Please login to merge, or discard this patch.
src/Collectors/ControllerCollectorTrait.php 2 patches
Braces   +9 added lines, -5 removed lines patch added patch discarded remove patch
@@ -69,8 +69,9 @@  discard block
 block discarded – undo
69 69
     public function controllers(array $controllers)
70 70
     {
71 71
         $group = new Group;
72
-        foreach ($controllers as $controller)
73
-            $group->set($this->controller($controller));
72
+        foreach ($controllers as $controller) {
73
+                    $group->set($this->controller($controller));
74
+        }
74 75
         return $group;
75 76
     }
76 77
 
@@ -100,8 +101,9 @@  discard block
 block discarded – undo
100 101
     public function controllersWithoutPrefix(array $controllers)
101 102
     {
102 103
         $group = new Group;
103
-        foreach ($controllers as $controller)
104
-            $group->set($this->controllerWithoutPrefix($controller));
104
+        foreach ($controllers as $controller) {
105
+                    $group->set($this->controllerWithoutPrefix($controller));
106
+        }
105 107
         return $group;
106 108
     }
107 109
 
@@ -134,7 +136,9 @@  discard block
 block discarded – undo
134 136
 
135 137
                 if ($strategy !== null) {
136 138
                        $route->setStrategy($strategy);
137
-                } else $route->setStrategy($controllerDefaultStrategy);
139
+                } else {
140
+                	$route->setStrategy($controllerDefaultStrategy);
141
+                }
138 142
 
139 143
                 $group->set($route);
140 144
             }
Please login to merge, or discard this patch.
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -26,223 +26,223 @@
 block discarded – undo
26 26
 trait ControllerCollectorTrait
27 27
 {
28 28
 
29
-    abstract public function getWildcards();
30
-    abstract public function set($method, $pattern, $action);
31
-
32
-    /**
33
-     * Define how controller actions names will be joined to form the route pattern.
34
-     *
35
-     * @var string
36
-     */
37
-
38
-    protected $controllerActionJoin = "/";
39
-
40
-    /**
41
-     * Maps all the controller methods that begins with a HTTP method, and maps the rest of
42
-     * name as a path. The path will be the method name with slashes before every camelcased 
43
-     * word and without the HTTP method prefix, and the controller name will be used to prefix
44
-     * the route pattern. e.g. ArticlesController::getCreate will generate a route to: GET articles/create
45
-     *
46
-     * @param string $controller The controller name
47
-     * @param string $prefix
48
-     *
49
-     * @throws \ReflectionException
50
-     * @return Group
51
-     */
52
-
53
-    public function controller($controller, $prefix = null)
54
-    {
55
-        $controller = new ReflectionClass($controller);
56
-        $prefix     = $prefix === null ? $this->getControllerPrefix($controller) : $prefix;
57
-        $methods    = $controller->getMethods(ReflectionMethod::IS_PUBLIC);
58
-        return $this->collectControllerRoutes($controller, $methods, "/$prefix/");
59
-    }
60
-
61
-    /**
62
-     * Maps several controllers at same time.
63
-     *
64
-     * @param string[] $controllers Controllers name.
65
-     * @throws \ReflectionException
66
-     * @return Group
67
-     */
68
-
69
-    public function controllers(array $controllers)
70
-    {
71
-        $group = new Group;
72
-        foreach ($controllers as $controller)
73
-            $group->set($this->controller($controller));
74
-        return $group;
75
-    }
76
-
77
-    /**
78
-     * Alias for Collector::controller but maps a controller without using the controller name as prefix.
79
-     *
80
-     * @param string $controller The controller name
81
-     * @throws \ReflectionException
82
-     * @return Group
83
-     */
84
-
85
-    public function controllerWithoutPrefix($controller)
86
-    {
87
-        $controller = new ReflectionClass($controller);
88
-        $methods = $controller->getMethods(ReflectionMethod::IS_PUBLIC);
89
-        return $this->collectControllerRoutes($controller, $methods, "/");
90
-    }
91
-
92
-    /**
93
-     * Alias for Collector::controllers but maps a controller without using the controller name as prefix.
94
-     *
95
-     * @param string[] $controllers
96
-     * @throws \ReflectionException
97
-     * @return Group
98
-     */
99
-
100
-    public function controllersWithoutPrefix(array $controllers)
101
-    {
102
-        $group = new Group;
103
-        foreach ($controllers as $controller)
104
-            $group->set($this->controllerWithoutPrefix($controller));
105
-        return $group;
106
-    }
107
-
108
-    /**
109
-     * @param ReflectionClass $controller
110
-     * @param ReflectionMethod[] $methods
111
-     * @param string $prefix
112
-     *
113
-     * @return Group
114
-     */
115
-
116
-    protected function collectControllerRoutes(ReflectionClass $controller, array $methods, $prefix)
117
-    {
118
-        $group = new Group;
119
-        $controllerDefaultStrategy = $this->getAnnotatedStrategy($controller);
120
-
121
-        foreach ($methods as $method) {
122
-            $name = preg_split("~(?=[A-Z])~", $method->name);
123
-            $http = $name[0];
124
-            unset($name[0]);
29
+	abstract public function getWildcards();
30
+	abstract public function set($method, $pattern, $action);
31
+
32
+	/**
33
+	 * Define how controller actions names will be joined to form the route pattern.
34
+	 *
35
+	 * @var string
36
+	 */
37
+
38
+	protected $controllerActionJoin = "/";
39
+
40
+	/**
41
+	 * Maps all the controller methods that begins with a HTTP method, and maps the rest of
42
+	 * name as a path. The path will be the method name with slashes before every camelcased 
43
+	 * word and without the HTTP method prefix, and the controller name will be used to prefix
44
+	 * the route pattern. e.g. ArticlesController::getCreate will generate a route to: GET articles/create
45
+	 *
46
+	 * @param string $controller The controller name
47
+	 * @param string $prefix
48
+	 *
49
+	 * @throws \ReflectionException
50
+	 * @return Group
51
+	 */
52
+
53
+	public function controller($controller, $prefix = null)
54
+	{
55
+		$controller = new ReflectionClass($controller);
56
+		$prefix     = $prefix === null ? $this->getControllerPrefix($controller) : $prefix;
57
+		$methods    = $controller->getMethods(ReflectionMethod::IS_PUBLIC);
58
+		return $this->collectControllerRoutes($controller, $methods, "/$prefix/");
59
+	}
60
+
61
+	/**
62
+	 * Maps several controllers at same time.
63
+	 *
64
+	 * @param string[] $controllers Controllers name.
65
+	 * @throws \ReflectionException
66
+	 * @return Group
67
+	 */
68
+
69
+	public function controllers(array $controllers)
70
+	{
71
+		$group = new Group;
72
+		foreach ($controllers as $controller)
73
+			$group->set($this->controller($controller));
74
+		return $group;
75
+	}
76
+
77
+	/**
78
+	 * Alias for Collector::controller but maps a controller without using the controller name as prefix.
79
+	 *
80
+	 * @param string $controller The controller name
81
+	 * @throws \ReflectionException
82
+	 * @return Group
83
+	 */
84
+
85
+	public function controllerWithoutPrefix($controller)
86
+	{
87
+		$controller = new ReflectionClass($controller);
88
+		$methods = $controller->getMethods(ReflectionMethod::IS_PUBLIC);
89
+		return $this->collectControllerRoutes($controller, $methods, "/");
90
+	}
91
+
92
+	/**
93
+	 * Alias for Collector::controllers but maps a controller without using the controller name as prefix.
94
+	 *
95
+	 * @param string[] $controllers
96
+	 * @throws \ReflectionException
97
+	 * @return Group
98
+	 */
99
+
100
+	public function controllersWithoutPrefix(array $controllers)
101
+	{
102
+		$group = new Group;
103
+		foreach ($controllers as $controller)
104
+			$group->set($this->controllerWithoutPrefix($controller));
105
+		return $group;
106
+	}
107
+
108
+	/**
109
+	 * @param ReflectionClass $controller
110
+	 * @param ReflectionMethod[] $methods
111
+	 * @param string $prefix
112
+	 *
113
+	 * @return Group
114
+	 */
115
+
116
+	protected function collectControllerRoutes(ReflectionClass $controller, array $methods, $prefix)
117
+	{
118
+		$group = new Group;
119
+		$controllerDefaultStrategy = $this->getAnnotatedStrategy($controller);
120
+
121
+		foreach ($methods as $method) {
122
+			$name = preg_split("~(?=[A-Z])~", $method->name);
123
+			$http = $name[0];
124
+			unset($name[0]);
125 125
  
126
-            if (strpos(Collector::HTTP_METHODS, $http) !== false) {
127
-                $action   = $prefix . strtolower(implode($this->controllerActionJoin, $name));
128
-                $dynamic  = $this->getMethodConstraints($method);
129
-                $strategy = $this->getAnnotatedStrategy($method);
130
-
131
-                /** @var \Codeburner\Router\Route $route */
132
-                $route = $this->set($http, "$action$dynamic", [$controller->name, $method->name]);
133
-
134
-                if ($strategy !== null) {
135
-                       $route->setStrategy($strategy);
136
-                } else $route->setStrategy($controllerDefaultStrategy);
137
-
138
-                $group->set($route);
139
-            }
140
-        }
141
-
142
-        return $group;
143
-    }
144
-
145
-    /**
146
-     * @param ReflectionClass $controller
147
-     *
148
-     * @return string
149
-     */
150
-
151
-    protected function getControllerPrefix(ReflectionClass $controller)
152
-    {
153
-        preg_match("~\@prefix\s([a-zA-Z\\\_]+)~i", (string) $controller->getDocComment(), $prefix);
154
-        return isset($prefix[1]) ? $prefix[1] : str_replace("controller", "", strtolower($controller->getShortName()));
155
-    }
156
-
157
-    /**
158
-     * @param \ReflectionMethod
159
-     * @return string
160
-     */
161
-
162
-    protected function getMethodConstraints(ReflectionMethod $method)
163
-    {
164
-        $beginPath = "";
165
-        $endPath = "";
166
-
167
-        if ($parameters = $method->getParameters()) {
168
-            $types = $this->getParamsConstraint($method);
169
-
170
-            foreach ($parameters as $parameter) {
171
-                if ($parameter->isOptional()) {
172
-                    $beginPath .= "[";
173
-                    $endPath .= "]";
174
-                }
175
-
176
-                $beginPath .= $this->getPathConstraint($parameter, $types);
177
-            }
178
-        }
179
-
180
-        return $beginPath . $endPath;
181
-    }
182
-
183
-    /**
184
-     * @param ReflectionParameter $parameter
185
-     * @param string[] $types
186
-     * @return string
187
-     */
188
-
189
-    protected function getPathConstraint(ReflectionParameter $parameter, $types)
190
-    {
191
-        $name = $parameter->name;
192
-        $path = "/{" . $name;
193
-        return isset($types[$name]) ? "$path:{$types[$name]}}" : "$path}";
194
-    }
195
-
196
-    /**
197
-     * @param ReflectionMethod $method
198
-     * @return string[]
199
-     */
200
-
201
-    protected function getParamsConstraint(ReflectionMethod $method)
202
-    {
203
-        $params = [];
204
-        preg_match_all("~\@param\s(" . implode("|", array_keys($this->getWildcards())) . "|\(.+\))\s\\$([a-zA-Z0-1_]+)~i",
205
-            $method->getDocComment(), $types, PREG_SET_ORDER);
206
-
207
-        foreach ((array) $types as $type) {
208
-            // if a pattern is defined on Match take it otherwise take the param type by PHPDoc.
209
-            $params[$type[2]] = isset($type[4]) ? $type[4] : $type[1];
210
-        }
211
-
212
-        return $params;
213
-    }
214
-
215
-    /**
216
-     * @param ReflectionClass|ReflectionMethod $reflector
217
-     * @return string|null
218
-     */
219
-
220
-    protected function getAnnotatedStrategy($reflector)
221
-    {
222
-        preg_match("~\@strategy\s([a-zA-Z\\\_]+)~i", (string) $reflector->getDocComment(), $strategy);
223
-        return isset($strategy[1]) ? $strategy[1] : null;
224
-    }
225
-
226
-    /**
227
-     * Define how controller actions names will be joined to form the route pattern.
228
-     * Defaults to "/" so actions like "getMyAction" will be "/my/action". If changed to
229
-     * "-" the new pattern will be "/my-action".
230
-     *
231
-     * @param string $join
232
-     */
233
-
234
-    public function setControllerActionJoin($join)
235
-    {
236
-        $this->controllerActionJoin = $join;
237
-    }
238
-
239
-    /**
240
-     * @return string
241
-     */
242
-
243
-    public function getControllerActionJoin()
244
-    {
245
-        return $this->controllerActionJoin;
246
-    }
126
+			if (strpos(Collector::HTTP_METHODS, $http) !== false) {
127
+				$action   = $prefix . strtolower(implode($this->controllerActionJoin, $name));
128
+				$dynamic  = $this->getMethodConstraints($method);
129
+				$strategy = $this->getAnnotatedStrategy($method);
130
+
131
+				/** @var \Codeburner\Router\Route $route */
132
+				$route = $this->set($http, "$action$dynamic", [$controller->name, $method->name]);
133
+
134
+				if ($strategy !== null) {
135
+					   $route->setStrategy($strategy);
136
+				} else $route->setStrategy($controllerDefaultStrategy);
137
+
138
+				$group->set($route);
139
+			}
140
+		}
141
+
142
+		return $group;
143
+	}
144
+
145
+	/**
146
+	 * @param ReflectionClass $controller
147
+	 *
148
+	 * @return string
149
+	 */
150
+
151
+	protected function getControllerPrefix(ReflectionClass $controller)
152
+	{
153
+		preg_match("~\@prefix\s([a-zA-Z\\\_]+)~i", (string) $controller->getDocComment(), $prefix);
154
+		return isset($prefix[1]) ? $prefix[1] : str_replace("controller", "", strtolower($controller->getShortName()));
155
+	}
156
+
157
+	/**
158
+	 * @param \ReflectionMethod
159
+	 * @return string
160
+	 */
161
+
162
+	protected function getMethodConstraints(ReflectionMethod $method)
163
+	{
164
+		$beginPath = "";
165
+		$endPath = "";
166
+
167
+		if ($parameters = $method->getParameters()) {
168
+			$types = $this->getParamsConstraint($method);
169
+
170
+			foreach ($parameters as $parameter) {
171
+				if ($parameter->isOptional()) {
172
+					$beginPath .= "[";
173
+					$endPath .= "]";
174
+				}
175
+
176
+				$beginPath .= $this->getPathConstraint($parameter, $types);
177
+			}
178
+		}
179
+
180
+		return $beginPath . $endPath;
181
+	}
182
+
183
+	/**
184
+	 * @param ReflectionParameter $parameter
185
+	 * @param string[] $types
186
+	 * @return string
187
+	 */
188
+
189
+	protected function getPathConstraint(ReflectionParameter $parameter, $types)
190
+	{
191
+		$name = $parameter->name;
192
+		$path = "/{" . $name;
193
+		return isset($types[$name]) ? "$path:{$types[$name]}}" : "$path}";
194
+	}
195
+
196
+	/**
197
+	 * @param ReflectionMethod $method
198
+	 * @return string[]
199
+	 */
200
+
201
+	protected function getParamsConstraint(ReflectionMethod $method)
202
+	{
203
+		$params = [];
204
+		preg_match_all("~\@param\s(" . implode("|", array_keys($this->getWildcards())) . "|\(.+\))\s\\$([a-zA-Z0-1_]+)~i",
205
+			$method->getDocComment(), $types, PREG_SET_ORDER);
206
+
207
+		foreach ((array) $types as $type) {
208
+			// if a pattern is defined on Match take it otherwise take the param type by PHPDoc.
209
+			$params[$type[2]] = isset($type[4]) ? $type[4] : $type[1];
210
+		}
211
+
212
+		return $params;
213
+	}
214
+
215
+	/**
216
+	 * @param ReflectionClass|ReflectionMethod $reflector
217
+	 * @return string|null
218
+	 */
219
+
220
+	protected function getAnnotatedStrategy($reflector)
221
+	{
222
+		preg_match("~\@strategy\s([a-zA-Z\\\_]+)~i", (string) $reflector->getDocComment(), $strategy);
223
+		return isset($strategy[1]) ? $strategy[1] : null;
224
+	}
225
+
226
+	/**
227
+	 * Define how controller actions names will be joined to form the route pattern.
228
+	 * Defaults to "/" so actions like "getMyAction" will be "/my/action". If changed to
229
+	 * "-" the new pattern will be "/my-action".
230
+	 *
231
+	 * @param string $join
232
+	 */
233
+
234
+	public function setControllerActionJoin($join)
235
+	{
236
+		$this->controllerActionJoin = $join;
237
+	}
238
+
239
+	/**
240
+	 * @return string
241
+	 */
242
+
243
+	public function getControllerActionJoin()
244
+	{
245
+		return $this->controllerActionJoin;
246
+	}
247 247
 
248 248
 }
Please login to merge, or discard this patch.
src/Group.php 2 patches
Braces   +39 added lines, -25 removed lines patch added patch discarded remove patch
@@ -37,9 +37,12 @@  discard block
 block discarded – undo
37 37
     public function set($route)
38 38
     {
39 39
         if ($route instanceof Group) {
40
-            foreach ($route->all() as $r)
41
-                $this->routes[] = $r;
42
-        } else  $this->routes[] = $route;
40
+            foreach ($route->all() as $r) {
41
+                            $this->routes[] = $r;
42
+            }
43
+        } else {
44
+        	$this->routes[] = $route;
45
+        }
43 46
         return  $this;
44 47
     }
45 48
 
@@ -88,8 +91,9 @@  discard block
 block discarded – undo
88 91
 
89 92
     public function forget()
90 93
     {
91
-        foreach ($this->routes as $route)
92
-            $route->forget();
94
+        foreach ($this->routes as $route) {
95
+                    $route->forget();
96
+        }
93 97
         return $this;
94 98
     }
95 99
 
@@ -102,8 +106,9 @@  discard block
 block discarded – undo
102 106
 
103 107
     public function setMethod($method)
104 108
     {
105
-        foreach ($this->routes as $route)
106
-            $route->setMethod($method);
109
+        foreach ($this->routes as $route) {
110
+                    $route->setMethod($method);
111
+        }
107 112
         return $this;
108 113
     }
109 114
 
@@ -116,8 +121,9 @@  discard block
 block discarded – undo
116 121
 
117 122
     public function setAction($action)
118 123
     {
119
-        foreach ($this->routes as $route)
120
-            $route->setAction($action);
124
+        foreach ($this->routes as $route) {
125
+                    $route->setAction($action);
126
+        }
121 127
         return $this;
122 128
     }
123 129
 
@@ -130,8 +136,9 @@  discard block
 block discarded – undo
130 136
 
131 137
     public function setNamespace($namespace)
132 138
     {
133
-        foreach ($this->routes as $route)
134
-            $route->setNamespace($namespace);
139
+        foreach ($this->routes as $route) {
140
+                    $route->setNamespace($namespace);
141
+        }
135 142
         return $this;
136 143
     }
137 144
 
@@ -145,8 +152,9 @@  discard block
 block discarded – undo
145 152
     public function setPrefix($prefix)
146 153
     {
147 154
         $prefix = "/" . ltrim($prefix, "/");
148
-        foreach ($this->routes as $route)
149
-            $route->setPattern(rtrim($prefix . $route->getPattern(), "/"));
155
+        foreach ($this->routes as $route) {
156
+                    $route->setPattern(rtrim($prefix . $route->getPattern(), "/"));
157
+        }
150 158
         return $this;
151 159
     }
152 160
 
@@ -161,8 +169,9 @@  discard block
 block discarded – undo
161 169
 
162 170
     public function setMetadata($key, $value)
163 171
     {
164
-        foreach ($this->routes as $route)
165
-            $route->setMetadata($key, $value);
172
+        foreach ($this->routes as $route) {
173
+                    $route->setMetadata($key, $value);
174
+        }
166 175
         return $this;
167 176
     }
168 177
 
@@ -175,8 +184,9 @@  discard block
 block discarded – undo
175 184
 
176 185
     public function setMetadataArray(array $metadata)
177 186
     {
178
-        foreach ($this->routes as $route)
179
-            $route->setMetadataArray($metadata);
187
+        foreach ($this->routes as $route) {
188
+                    $route->setMetadataArray($metadata);
189
+        }
180 190
         return $this;
181 191
     }
182 192
 
@@ -189,8 +199,9 @@  discard block
 block discarded – undo
189 199
 
190 200
     public function setDefaults(array $defaults)
191 201
     {
192
-        foreach ($this->routes as $route)
193
-            $route->setDefaults($defaults);
202
+        foreach ($this->routes as $route) {
203
+                    $route->setDefaults($defaults);
204
+        }
194 205
         return $this;
195 206
     }
196 207
 
@@ -205,8 +216,9 @@  discard block
 block discarded – undo
205 216
 
206 217
     public function setDefault($key, $value)
207 218
     {
208
-        foreach ($this->routes as $route)
209
-            $route->setDefault($key, $value);
219
+        foreach ($this->routes as $route) {
220
+                    $route->setDefault($key, $value);
221
+        }
210 222
         return $this;
211 223
     }
212 224
 
@@ -219,8 +231,9 @@  discard block
 block discarded – undo
219 231
 
220 232
     public function setStrategy($strategy)
221 233
     {
222
-        foreach ($this->routes as $route)
223
-            $route->setStrategy($strategy);
234
+        foreach ($this->routes as $route) {
235
+                    $route->setStrategy($strategy);
236
+        }
224 237
         return $this;
225 238
     }
226 239
 
@@ -235,8 +248,9 @@  discard block
 block discarded – undo
235 248
 
236 249
     public function setConstraint($name, $regex)
237 250
     {
238
-        foreach ($this->routes as $route)
239
-            $route->setConstraint($name, $regex);
251
+        foreach ($this->routes as $route) {
252
+                    $route->setConstraint($name, $regex);
253
+        }
240 254
         return $this;
241 255
     }
242 256
 
Please login to merge, or discard this patch.
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -19,227 +19,227 @@
 block discarded – undo
19 19
 class Group
20 20
 {
21 21
 
22
-    /**
23
-     * All grouped route objects.
24
-     *
25
-     * @var Route[]
26
-     */
27
-
28
-    protected $routes;
29
-
30
-    /**
31
-     * Set a new Route or merge an existing group of routes.
32
-     *
33
-     * @param Group|Route $route
34
-     * @return self
35
-     */
36
-
37
-    public function set($route)
38
-    {
39
-        if ($route instanceof Group) {
40
-            foreach ($route->all() as $r)
41
-                $this->routes[] = $r;
42
-        } else  $this->routes[] = $route;
43
-        return  $this;
44
-    }
45
-
46
-    /**
47
-     * A fast way to register a route into the group
48
-     *
49
-     * @param Route $route
50
-     * @return self
51
-     */
52
-
53
-    public function setRoute(Route $route)
54
-    {
55
-        $this->routes[] = $route;
56
-        return $this;
57
-    }
58
-
59
-    /**
60
-     * Return all grouped routes objects.
61
-     *
62
-     * @return Route[]
63
-     */
64
-
65
-    public function all()
66
-    {
67
-        return $this->routes;
68
-    }
69
-
70
-    /**
71
-     * Get a specific route of the group, routes receive a key based on
72
-     * the order they are added to the group.
73
-     *
74
-     * @param int $number
75
-     * @return Route
76
-     */
77
-
78
-    public function nth($number)
79
-    {
80
-        return $this->routes[$number];
81
-    }
82
-
83
-    /**
84
-     * Forget the registration of all grouped routes on to collector.
85
-     * After the forget the route object will still exist but will not
86
-     * count for the matcher.
87
-     *
88
-     * @return self
89
-     */
90
-
91
-    public function forget()
92
-    {
93
-        foreach ($this->routes as $route)
94
-            $route->forget();
95
-        return $this;
96
-    }
97
-
98
-    /**
99
-     * Set one HTTP method to all grouped routes.
100
-     *
101
-     * @param string $method The HTTP Method
102
-     * @return self
103
-     */
104
-
105
-    public function setMethod($method)
106
-    {
107
-        foreach ($this->routes as $route)
108
-            $route->setMethod($method);
109
-        return $this;
110
-    }
111
-
112
-    /**
113
-     * Set one action to all grouped routes.
114
-     *
115
-     * @param string $action
116
-     * @return self
117
-     */
118
-
119
-    public function setAction($action)
120
-    {
121
-        foreach ($this->routes as $route)
122
-            $route->setAction($action);
123
-        return $this;
124
-    }
125
-
126
-    /**
127
-     * Set one namespace to all grouped routes.
128
-     *
129
-     * @param string $namespace
130
-     * @return self
131
-     */
132
-
133
-    public function setNamespace($namespace)
134
-    {
135
-        foreach ($this->routes as $route)
136
-            $route->setNamespace($namespace);
137
-        return $this;
138
-    }
139
-
140
-    /**
141
-     * Add a prefix to all grouped routes pattern.
142
-     *
143
-     * @param string $prefix
144
-     * @return self
145
-     */
146
-
147
-    public function setPrefix($prefix)
148
-    {
149
-        $prefix = "/" . ltrim($prefix, "/");
150
-        foreach ($this->routes as $route)
151
-            $route->setPattern(rtrim($prefix . $route->getPattern(), "/"));
152
-        return $this;
153
-    }
154
-
155
-    /**
156
-     * Set metadata to all grouped routes.
157
-     *
158
-     * @param string $key
159
-     * @param string $value
160
-     *
161
-     * @return $this
162
-     */
163
-
164
-    public function setMetadata($key, $value)
165
-    {
166
-        foreach ($this->routes as $route)
167
-            $route->setMetadata($key, $value);
168
-        return $this;
169
-    }
170
-
171
-    /**
172
-     * Set a bunch of metadata to all grouped routes.
173
-     *
174
-     * @param mixed[] $metadata
175
-     * @return $this
176
-     */
177
-
178
-    public function setMetadataArray(array $metadata)
179
-    {
180
-        foreach ($this->routes as $route)
181
-            $route->setMetadataArray($metadata);
182
-        return $this;
183
-    }
184
-
185
-    /**
186
-     * Set default parameters to all grouped routes.
187
-     *
188
-     * @param mixed[] $defaults
189
-     * @return $this
190
-     */
191
-
192
-    public function setDefaults(array $defaults)
193
-    {
194
-        foreach ($this->routes as $route)
195
-            $route->setDefaults($defaults);
196
-        return $this;
197
-    }
198
-
199
-    /**
200
-     * Set a default parameter to all grouped routes.
201
-     *
202
-     * @param string $key
203
-     * @param mixed $value
204
-     *
205
-     * @return $this
206
-     */
207
-
208
-    public function setDefault($key, $value)
209
-    {
210
-        foreach ($this->routes as $route)
211
-            $route->setDefault($key, $value);
212
-        return $this;
213
-    }
214
-
215
-    /**
216
-     * Set one dispatch strategy to all grouped routes.
217
-     *
218
-     * @param string|Strategies\StrategyInterface $strategy
219
-     * @return self
220
-     */
221
-
222
-    public function setStrategy($strategy)
223
-    {
224
-        foreach ($this->routes as $route)
225
-            $route->setStrategy($strategy);
226
-        return $this;
227
-    }
228
-
229
-    /**
230
-     * Replace or define a constraint for all dynamic segments named by $name.
231
-     *
232
-     * @param string $name
233
-     * @param string $regex
234
-     *
235
-     * @return self
236
-     */
237
-
238
-    public function setConstraint($name, $regex)
239
-    {
240
-        foreach ($this->routes as $route)
241
-            $route->setConstraint($name, $regex);
242
-        return $this;
243
-    }
22
+	/**
23
+	 * All grouped route objects.
24
+	 *
25
+	 * @var Route[]
26
+	 */
27
+
28
+	protected $routes;
29
+
30
+	/**
31
+	 * Set a new Route or merge an existing group of routes.
32
+	 *
33
+	 * @param Group|Route $route
34
+	 * @return self
35
+	 */
36
+
37
+	public function set($route)
38
+	{
39
+		if ($route instanceof Group) {
40
+			foreach ($route->all() as $r)
41
+				$this->routes[] = $r;
42
+		} else  $this->routes[] = $route;
43
+		return  $this;
44
+	}
45
+
46
+	/**
47
+	 * A fast way to register a route into the group
48
+	 *
49
+	 * @param Route $route
50
+	 * @return self
51
+	 */
52
+
53
+	public function setRoute(Route $route)
54
+	{
55
+		$this->routes[] = $route;
56
+		return $this;
57
+	}
58
+
59
+	/**
60
+	 * Return all grouped routes objects.
61
+	 *
62
+	 * @return Route[]
63
+	 */
64
+
65
+	public function all()
66
+	{
67
+		return $this->routes;
68
+	}
69
+
70
+	/**
71
+	 * Get a specific route of the group, routes receive a key based on
72
+	 * the order they are added to the group.
73
+	 *
74
+	 * @param int $number
75
+	 * @return Route
76
+	 */
77
+
78
+	public function nth($number)
79
+	{
80
+		return $this->routes[$number];
81
+	}
82
+
83
+	/**
84
+	 * Forget the registration of all grouped routes on to collector.
85
+	 * After the forget the route object will still exist but will not
86
+	 * count for the matcher.
87
+	 *
88
+	 * @return self
89
+	 */
90
+
91
+	public function forget()
92
+	{
93
+		foreach ($this->routes as $route)
94
+			$route->forget();
95
+		return $this;
96
+	}
97
+
98
+	/**
99
+	 * Set one HTTP method to all grouped routes.
100
+	 *
101
+	 * @param string $method The HTTP Method
102
+	 * @return self
103
+	 */
104
+
105
+	public function setMethod($method)
106
+	{
107
+		foreach ($this->routes as $route)
108
+			$route->setMethod($method);
109
+		return $this;
110
+	}
111
+
112
+	/**
113
+	 * Set one action to all grouped routes.
114
+	 *
115
+	 * @param string $action
116
+	 * @return self
117
+	 */
118
+
119
+	public function setAction($action)
120
+	{
121
+		foreach ($this->routes as $route)
122
+			$route->setAction($action);
123
+		return $this;
124
+	}
125
+
126
+	/**
127
+	 * Set one namespace to all grouped routes.
128
+	 *
129
+	 * @param string $namespace
130
+	 * @return self
131
+	 */
132
+
133
+	public function setNamespace($namespace)
134
+	{
135
+		foreach ($this->routes as $route)
136
+			$route->setNamespace($namespace);
137
+		return $this;
138
+	}
139
+
140
+	/**
141
+	 * Add a prefix to all grouped routes pattern.
142
+	 *
143
+	 * @param string $prefix
144
+	 * @return self
145
+	 */
146
+
147
+	public function setPrefix($prefix)
148
+	{
149
+		$prefix = "/" . ltrim($prefix, "/");
150
+		foreach ($this->routes as $route)
151
+			$route->setPattern(rtrim($prefix . $route->getPattern(), "/"));
152
+		return $this;
153
+	}
154
+
155
+	/**
156
+	 * Set metadata to all grouped routes.
157
+	 *
158
+	 * @param string $key
159
+	 * @param string $value
160
+	 *
161
+	 * @return $this
162
+	 */
163
+
164
+	public function setMetadata($key, $value)
165
+	{
166
+		foreach ($this->routes as $route)
167
+			$route->setMetadata($key, $value);
168
+		return $this;
169
+	}
170
+
171
+	/**
172
+	 * Set a bunch of metadata to all grouped routes.
173
+	 *
174
+	 * @param mixed[] $metadata
175
+	 * @return $this
176
+	 */
177
+
178
+	public function setMetadataArray(array $metadata)
179
+	{
180
+		foreach ($this->routes as $route)
181
+			$route->setMetadataArray($metadata);
182
+		return $this;
183
+	}
184
+
185
+	/**
186
+	 * Set default parameters to all grouped routes.
187
+	 *
188
+	 * @param mixed[] $defaults
189
+	 * @return $this
190
+	 */
191
+
192
+	public function setDefaults(array $defaults)
193
+	{
194
+		foreach ($this->routes as $route)
195
+			$route->setDefaults($defaults);
196
+		return $this;
197
+	}
198
+
199
+	/**
200
+	 * Set a default parameter to all grouped routes.
201
+	 *
202
+	 * @param string $key
203
+	 * @param mixed $value
204
+	 *
205
+	 * @return $this
206
+	 */
207
+
208
+	public function setDefault($key, $value)
209
+	{
210
+		foreach ($this->routes as $route)
211
+			$route->setDefault($key, $value);
212
+		return $this;
213
+	}
214
+
215
+	/**
216
+	 * Set one dispatch strategy to all grouped routes.
217
+	 *
218
+	 * @param string|Strategies\StrategyInterface $strategy
219
+	 * @return self
220
+	 */
221
+
222
+	public function setStrategy($strategy)
223
+	{
224
+		foreach ($this->routes as $route)
225
+			$route->setStrategy($strategy);
226
+		return $this;
227
+	}
228
+
229
+	/**
230
+	 * Replace or define a constraint for all dynamic segments named by $name.
231
+	 *
232
+	 * @param string $name
233
+	 * @param string $regex
234
+	 *
235
+	 * @return self
236
+	 */
237
+
238
+	public function setConstraint($name, $regex)
239
+	{
240
+		foreach ($this->routes as $route)
241
+			$route->setConstraint($name, $regex);
242
+		return $this;
243
+	}
244 244
 
245 245
 }
Please login to merge, or discard this patch.