Skip to content

Commit 294748b

Browse files
committed
Parse request uri with custom regex pattern
Can now parse URI like `/assets/:type/(.+)` where: * :type is a named parameter (can be "img", "css" or "js" in the example) * (.+) is global pattern (represent the path to the asset in the example) Global patterns are accessed by position and named parameters are accessed by name: ```php $params = $req->uri->getParams(); $assetType = $params['type']; // Get the value of `:type` in the URI $assetPath = $params[1]; // Get the value of `(.+)` in the URI // Note that the position is 1 because `:type` use the position 0 ```
1 parent 25f4f57 commit 294748b

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/WaterPipe/HTTP/Request/RequestUri.php

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,35 @@ public function build()
119119
preg_match("#^{$regex}\$#", $this->_uri, $values);
120120
array_shift($values);
121121

122-
$this->_params = array_combine($params, $values);
122+
if (count($params) > 0) {
123+
if (count($params) < count($values)) {
124+
$parts = explode("/", trim($this->_pattern, "/"));
125+
$pos = array();
126+
$count = 0;
127+
128+
foreach ($parts as $key => $value) {
129+
if (!empty($value)) {
130+
if (preg_match("#^([a-zA-Z0-9-_\.]+)$#", $value)) {
131+
continue;
132+
} else {
133+
if (in_array(trim($value, ":"), $params, true)) {
134+
$pos[$count] = trim($value, ":");
135+
} else {
136+
$pos[$count] = $count;
137+
}
138+
139+
$count++;
140+
}
141+
}
142+
}
143+
144+
$params = $pos;
145+
}
146+
147+
$this->_params = array_combine($params, $values);
148+
} else {
149+
$this->_params = $values;
150+
}
123151

124152
$this->_built = true;
125153
} else {

0 commit comments

Comments
 (0)