Skip to content

Commit c6d074e

Browse files
davidkrmeladg
authored andcommitted
Route: add %host% variable (#140)
1 parent 66a862e commit c6d074e

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

src/Application/Routers/Route.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,12 +161,13 @@ public function match(Nette\Http\IRequest $httpRequest)
161161
if ($this->type === self::HOST) {
162162
$host = $url->getHost();
163163
$path = '//' . $host . $url->getPath();
164-
$host = ip2long($host) ? [$host] : array_reverse(explode('.', $host));
164+
$parts = ip2long($host) ? [$host] : array_reverse(explode('.', $host));
165165
$re = strtr($re, [
166166
'/%basePath%/' => preg_quote($url->getBasePath(), '#'),
167-
'%tld%' => preg_quote($host[0], '#'),
168-
'%domain%' => preg_quote(isset($host[1]) ? "$host[1].$host[0]" : $host[0], '#'),
169-
'%sld%' => preg_quote(isset($host[1]) ? $host[1] : '', '#'),
167+
'%tld%' => preg_quote($parts[0], '#'),
168+
'%domain%' => preg_quote(isset($parts[1]) ? "$parts[1].$parts[0]" : $parts[0], '#'),
169+
'%sld%' => preg_quote(isset($parts[1]) ? $parts[1] : '', '#'),
170+
'%host%' => preg_quote($host, '#'),
170171
]);
171172

172173
} elseif ($this->type === self::RELATIVE) {
@@ -400,6 +401,7 @@ public function constructUrl(Application\Request $appRequest, Nette\Http\Url $re
400401
'%tld%' => $parts[0],
401402
'%domain%' => isset($parts[1]) ? "$parts[1].$parts[0]" : $parts[0],
402403
'%sld%' => isset($parts[1]) ? $parts[1] : '',
404+
'%host%' => $host,
403405
]);
404406
$url = ($this->scheme ?: $refUrl->getScheme()) . ':' . $url;
405407
} else {

tests/Routers/Route.variables.phpt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ testRouteIn(new Route('//%sld%.%tld%/<path>', 'Default:default'), '/abc', 'Defau
5555
], '/abc?test=testvalue');
5656

5757

58+
testRouteIn(new Route('//%host%/<path>', 'Default:default'), '/abc', 'Default', [
59+
'path' => 'abc',
60+
'action' => 'default',
61+
'test' => 'testvalue',
62+
], '/abc?test=testvalue');
63+
64+
5865
// alternative
5966
testRouteIn(new Route('//example.%tld%/<path>', 'Default:default'), '/abc', 'Default', [
6067
'path' => 'abc',
@@ -97,3 +104,10 @@ Assert::same('http://localhost/', $route->constructUrl($route->match($httpReques
97104

98105
$route = new Route('//%tld%/', 'Default:default');
99106
Assert::same('http://localhost/', $route->constructUrl($route->match($httpRequest), $url));
107+
108+
109+
// host
110+
$url = new Nette\Http\UrlScript('http://www.example.com/');
111+
$httpRequest = new Nette\Http\Request($url);
112+
$route = new Route('//%host%/', 'Default:default');
113+
Assert::same('http://www.example.com/', $route->constructUrl($route->match($httpRequest), $url));

0 commit comments

Comments
 (0)