Skip to content

Commit a4b9431

Browse files
committed
Merge branch 'urlFor'
Closes #102 Fixes #101
2 parents 7cb5289 + ddf84a3 commit a4b9431

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/TwigExtension.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
*/
99
namespace Slim\Views;
1010

11+
use Slim\Http\Uri;
12+
1113
class TwigExtension extends \Twig\Extension\AbstractExtension
1214
{
1315
/**
@@ -35,6 +37,7 @@ public function getFunctions()
3537
{
3638
return [
3739
new \Twig\TwigFunction('path_for', array($this, 'pathFor')),
40+
new \Twig\TwigFunction('full_url_for', array($this, 'fullUrlFor')),
3841
new \Twig\TwigFunction('base_url', array($this, 'baseUrl')),
3942
new \Twig\TwigFunction('is_current_path', array($this, 'isCurrentPath')),
4043
new \Twig\TwigFunction('current_path', array($this, 'currentPath')),
@@ -46,6 +49,35 @@ public function pathFor($name, $data = [], $queryParams = [], $appName = 'defaul
4649
return $this->router->pathFor($name, $data, $queryParams);
4750
}
4851

52+
/**
53+
* Similar to pathFor but returns a fully qualified URL
54+
*
55+
* @param string $name The name of the route
56+
* @param array $data Route placeholders
57+
* @param array $queryParams
58+
* @param string $appName
59+
* @return string fully qualified URL
60+
*/
61+
public function fullUrlFor($name, $data = [], $queryParams = [], $appName = 'default')
62+
{
63+
$path = $this->pathFor($name, $data, $queryParams, $appName);
64+
65+
/** @var Uri $uri */
66+
if (is_string($this->uri)) {
67+
$uri = Uri::createFromString($this->uri);
68+
} else {
69+
$uri = $this->uri;
70+
}
71+
72+
$scheme = $uri->getScheme();
73+
$authority = $uri->getAuthority();
74+
75+
$host = ($scheme ? $scheme . ':' : '')
76+
. ($authority ? '//' . $authority : '');
77+
78+
return $host.$path;
79+
}
80+
4981
public function baseUrl()
5082
{
5183
if (is_string($this->uri)) {

tests/TwigExtensionTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,18 @@ public function testCurrentPath($router, $uri, $withQueryString, $expected)
7474

7575
$this->assertEquals($expected, $result);
7676
}
77+
78+
public function testFullUrlFor()
79+
{
80+
$router = new Router();
81+
$router->setBasePath('/app');
82+
$router->map(['GET'], '/activate/{token}', null)->setName('activate');
83+
$uri = Uri::createFromString('http://example.com/app/hello/world?a=b');
84+
85+
$extension = new TwigExtension($router, $uri);
86+
$result = $extension->fullUrlFor('activate', ['token' => 'foo']);
87+
88+
$expected = 'http://example.com/app/activate/foo';
89+
$this->assertEquals($expected, $result);
90+
}
7791
}

0 commit comments

Comments
 (0)