This repository has been archived by the owner on Jan 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Segment.php
433 lines (370 loc) · 13.1 KB
/
Segment.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Mvc
*/
namespace Zend\Mvc\Router\Http;
use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;
/**
* Segment route.
*
* @package Zend_Mvc_Router
* @subpackage Http
* @see http://guides.rubyonrails.org/routing.html
*/
class Segment implements RouteInterface
{
/**
* @var array Cache for the encode output
*/
private static $__cacheEncode = array();
/**
* Map of allowed special chars in path segments.
*
* http://tools.ietf.org/html/rfc3986#appendix-A
* segement = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*
* @var array
*/
private static $urlencodeCorrectionMap = array(
'%21' => "!", // sub-delims
'%24' => "$", // sub-delims
'%26' => "&", // sub-delims
'%27' => "'", // sub-delims
'%28' => "(", // sub-delims
'%29' => ")", // sub-delims
'%2A' => "*", // sub-delims
'%2B' => "+", // sub-delims
'%2C' => ",", // sub-delims
// '%2D' => "-", // unreserved - not touched by rawurlencode
// '%2E' => ".", // unreserved - not touched by rawurlencode
'%3A' => ":", // pchar
'%3B' => ";", // sub-delims
'%3D' => "=", // sub-delims
'%40' => "@", // pchar
// '%5F' => "_", // unreserved - not touched by rawurlencode
'%7E' => "~", // unreserved
);
/**
* Parts of the route.
*
* @var array
*/
protected $parts;
/**
* Regex used for matching the route.
*
* @var string
*/
protected $regex;
/**
* Map from regex groups to parameter names.
*
* @var array
*/
protected $paramMap = array();
/**
* Default values.
*
* @var array
*/
protected $defaults;
/**
* List of assembled parameters.
*
* @var array
*/
protected $assembledParams = array();
/**
* Create a new regex route.
*
* @param string $route
* @param array $constraints
* @param array $defaults
*/
public function __construct($route, array $constraints = array(), array $defaults = array())
{
$this->defaults = $defaults;
$this->parts = $this->parseRouteDefinition($route);
$this->regex = $this->buildRegex($this->parts, $constraints);
}
/**
* factory(): defined by RouteInterface interface.
*
* @see Route::factory()
* @param array|Traversable $options
* @throws \Zend\Mvc\Router\Exception\InvalidArgumentException
* @return Segment
*/
public static function factory($options = array())
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
} elseif (!is_array($options)) {
throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable set of options');
}
if (!isset($options['route'])) {
throw new Exception\InvalidArgumentException('Missing "route" in options array');
}
if (!isset($options['constraints'])) {
$options['constraints'] = array();
}
if (!isset($options['defaults'])) {
$options['defaults'] = array();
}
return new static($options['route'], $options['constraints'], $options['defaults']);
}
/**
* Parse a route definition.
*
* @param string $def
* @return array
* @throws Exception\RuntimeException
*/
protected function parseRouteDefinition($def)
{
$currentPos = 0;
$length = strlen($def);
$parts = array();
$levelParts = array(&$parts);
$level = 0;
while ($currentPos < $length) {
preg_match('(\G(?P<literal>[^:{\[\]]*)(?P<token>[:{\[\]]|$))', $def, $matches, 0, $currentPos);
$currentPos += strlen($matches[0]);
if (!empty($matches['literal'])) {
$levelParts[$level][] = array('literal', $matches['literal']);
}
if ($matches['token'] === ':') {
if (isset($def[$currentPos]) && $def[$currentPos] === '{') {
if (!preg_match('(\G\{(?P<name>[^}]+)\}:?)', $def, $matches, 0, $currentPos)) {
throw new Exception\RuntimeException('Translated parameter missing closing bracket');
}
$levelParts[$level][] = array('translated-parameter', $matches['name']);
} else {
if (!preg_match('(\G(?P<name>[^:/{\[\]]+)(?:{(?P<delimiters>[^}]+)})?:?)', $def, $matches, 0, $currentPos)) {
throw new Exception\RuntimeException('Found empty parameter name');
}
$levelParts[$level][] = array('parameter', $matches['name'], isset($matches['delimiters']) ? $matches['delimiters'] : null);
}
$currentPos += strlen($matches[0]);
} elseif ($matches['token'] === '{') {
if (!preg_match('(\G(?P<literal>[^}]+)\})', $def, $matches, 0, $currentPos)) {
throw new Exception\RuntimeException('Translated literal missing closing bracket');
}
$currentPos += strlen($matches[0]);
$levelParts[$level][] = array('translated-literal', $matches['literal']);
} elseif ($matches['token'] === '[') {
$levelParts[$level][] = array('optional', array());
$levelParts[$level + 1] = &$levelParts[$level][count($levelParts[$level]) - 1][1];
$level++;
} elseif ($matches['token'] === ']') {
unset($levelParts[$level]);
$level--;
if ($level < 0) {
throw new Exception\RuntimeException('Found closing bracket without matching opening bracket');
}
} else {
break;
}
}
if ($level > 0) {
throw new Exception\RuntimeException('Found unbalanced brackets');
}
return $parts;
}
/**
* Build the matching regex from parsed parts.
*
* @param array $parts
* @param array $constraints
* @param integer $groupIndex
* @return string
* @throws Exception\RuntimeException
*/
protected function buildRegex(array $parts, array $constraints, &$groupIndex = 1)
{
$regex = '';
foreach ($parts as $part) {
switch ($part[0]) {
case 'literal':
$regex .= preg_quote($part[1]);
break;
case 'parameter':
$groupName = '?P<param' . $groupIndex . '>';
if (isset($constraints[$part[1]])) {
$regex .= '(' . $groupName . $constraints[$part[1]] . ')';
} elseif ($part[2] === null) {
$regex .= '(' . $groupName . '[^/]+)';
} else {
$regex .= '(' . $groupName . '[^' . $part[2] . ']+)';
}
$this->paramMap['param' . $groupIndex++] = $part[1];
break;
case 'optional':
$regex .= '(?:' . $this->buildRegex($part[1], $constraints, $groupIndex) . ')?';
break;
// @codeCoverageIgnoreStart
case 'translated-literal':
throw new Exception\RuntimeException('Translated literals are not implemented yet');
break;
case 'translated-parameter':
throw new Exception\RuntimeException('Translated parameters are not implemented yet');
break;
// @codeCoverageIgnoreEnd
}
}
return $regex;
}
/**
* Build a path.
*
* @param array $parts
* @param array $mergedParams
* @param boolean $isOptional
* @param boolean $hasChild
* @return string
* @throws Exception\RuntimeException
* @throws Exception\InvalidArgumentException
*/
protected function buildPath(array $parts, array $mergedParams, $isOptional, $hasChild)
{
$path = '';
$skip = true;
$skippable = false;
foreach ($parts as $part) {
switch ($part[0]) {
case 'literal':
$path .= $part[1];
break;
case 'parameter':
$skippable = true;
if (!isset($mergedParams[$part[1]])) {
if (!$isOptional || $hasChild) {
throw new Exception\InvalidArgumentException(sprintf('Missing parameter "%s"', $part[1]));
}
return '';
} elseif (!$isOptional || $hasChild || !isset($this->defaults[$part[1]]) || $this->defaults[$part[1]] !== $mergedParams[$part[1]]) {
$skip = false;
}
$path .= $this->encode($mergedParams[$part[1]]);
$this->assembledParams[] = $part[1];
break;
case 'optional':
$skippable = true;
$optionalPart = $this->buildPath($part[1], $mergedParams, true, $hasChild);
if ($optionalPart !== '') {
$path .= $optionalPart;
$skip = false;
}
break;
// @codeCoverageIgnoreStart
case 'translated-literal':
throw new Exception\RuntimeException('Translated literals are not implemented yet');
break;
case 'translated-parameter':
throw new Exception\RuntimeException('Translated parameters are not implemented yet');
break;
// @codeCoverageIgnoreEnd
}
}
if ($isOptional && $skippable && $skip) {
return '';
}
return $path;
}
/**
* match(): defined by RouteInterface interface.
*
* @see Route::match()
* @param Request $request
* @param string|null $pathOffset
* @return RouteMatch
*/
public function match(Request $request, $pathOffset = null)
{
if (!method_exists($request, 'getUri')) {
return null;
}
$uri = $request->getUri();
$path = $uri->getPath();
if ($pathOffset !== null) {
$result = preg_match('(\G' . $this->regex . ')', $path, $matches, null, $pathOffset);
} else {
$result = preg_match('(^' . $this->regex . '$)', $path, $matches);
}
if (!$result) {
return null;
}
$matchedLength = strlen($matches[0]);
$params = array();
foreach ($this->paramMap as $index => $name) {
if (isset($matches[$index]) && $matches[$index] !== '') {
$params[$name] = $this->decode($matches[$index]);
}
}
return new RouteMatch(array_merge($this->defaults, $params), $matchedLength);
}
/**
* assemble(): Defined by RouteInterface interface.
*
* @see Route::assemble()
* @param array $params
* @param array $options
* @return mixed
*/
public function assemble(array $params = array(), array $options = array())
{
$this->assembledParams = array();
return $this->buildPath(
$this->parts,
array_merge($this->defaults, $params),
false,
(isset($options['has_child']) ? $options['has_child'] : false)
);
}
/**
* getAssembledParams(): defined by RouteInterface interface.
*
* @see Route::getAssembledParams
* @return array
*/
public function getAssembledParams()
{
return $this->assembledParams;
}
/**
* Encode a path segment.
*
* @param string $value
* @return string
*/
private function encode($value)
{
if (!isset(static::$__cacheEncode[$value])) {
static::$__cacheEncode[$value] = rawurlencode($value);
static::$__cacheEncode[$value] = strtr(static::$__cacheEncode[$value], static::$urlencodeCorrectionMap);
}
return static::$__cacheEncode[$value];
}
/**
* Decode a path segment.
*
* @param string $value
* @return string
*/
private function decode($value)
{
return rawurldecode($value);
}
}