8000 feature #13264 URL manipulations as a Twig extension (fabpot) · symfony/symfony@861804b · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 861804b

Browse files
committed
feature #13264 URL manipulations as a Twig extension (fabpot)
This PR was merged into the 2.7 branch. Discussion ---------- URL manipulations as a Twig extension | Q | A | ------------- | --- | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | n/a | License | MIT | Doc PR | symfony/symfony-docs#4805 While working on the new asset component, I realized that the "absolute URL" feature was misplaced and would benefit from being exposed as a Twig function (composition is always a good thing). Then, I wondered if having a Twig function to generate a relative path (like done by the Routing component would also make sense). And here is the corresponding PR. ```jinja {# generate an absolute URL for the given absolute path #} {{ absolute_url('/me.png') }} {# generate a relative path for the given absolute path (based on the current Request) #} {{ relative_path('/foo/me.png') }} {# compose as you see fit #} {{ absolute_url(asset('me.png')) }} ``` As you can see, we require an absolute path for both functions (and we even add the leading slash if it is omitted), not sure if we want to do otherwise. ping @Tobion Commits ------- 0ec852d added a relative_path Twig function ee27ed8 added an absolute_url() Twig function
2 parents 545e1a4 + 0ec852d commit 861804b

File tree

7 files changed

+270
-0
lines changed

7 files changed

+270
-0
lines changed

src/Symfony/Bridge/Twig/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
2.7.0
5+
-----
6+
7+
* added an HttpFoundation extension (provides the `absolute_url` and the `relative_path` functions)
8+
49
2.5.0
510
-----
611

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bridge\Twig\Extension;
13+
14+
use Symfony\Component\HttpFoundation\RequestStack;
15+
use Symfony\Component\HttpFoundation\Request;
16+
17+
/**
18+
* Twig extension for the Symfony HttpFoundation component.
19+
*
20+
* @author Fabien Potencier <fabien@symfony.com>
21+
*/
22+
class HttpFoundationExtension extends \Twig_Extension
23+
{
24+
private $requestStack;
25+
26+
public function __construct(RequestStack $requestStack)
27+
{
28+
$this->requestStack = $requestStack;
29+
}
30+
31+
/**
32+
* {@inheritdoc}
33+
*/
34+
public function getFunctions()
35+
{
36+
return array(
37+
new \Twig_SimpleFunction('absolute_url', array($this, 'generateAbsoluteUrl')),
38+
new \Twig_SimpleFunction('relative_path', array($this, 'generateRelativePath')),
39+
);
40+
}
41+
42+
/**
43+
* Returns the absolute URL for the given absolute or relative path.
44+
*
45+
* This method returns the path unchanged if no request is available.
46+
*
47+
* @param string $path The path
48+
*
49+
* @return string The absolute URL
50+
*
51+
* @see Request::getUriForPath()
52+
*/
53+
public function generateAbsoluteUrl($path)
54+
{
55+
if (false !== strpos($path, '://') || '//' === substr($path, 0, 2)) {
56+
return $path;
57+
}
58+
59+
if (!$request = $this->requestStack->getMasterRequest()) {
60+
return $path;
61+
}
62+
63+
if (!$path || '/' !== $path[0]) {
64+
$prefix = $request->getPathInfo();
65+
$last = strlen($prefix) - 1;
66+
if ($last !== $pos = strrpos($prefix, '/')) {
67+
$prefix = substr($prefix, 0, $pos).'/';
68+
}
69+
70+
$path = $prefix.$path;
71+
}
72+
73+
return $request->getUriForPath($path);
74+
}
75+
76+
/**
77+
* Returns a relative path based on the current Request.
78+
*
79+
* This method returns the path unchanged if no request is available.
80+
*
81+
* @param string $path The path
82+
*
83+
* @return string The relative path
84+
*
85+
* @see Request::getRelativeUriForPath()
86+
*/
87+
public function generateRelativePath($path)
88+
{
89+
if (false !== strpos($path, '://') || '//' === substr($path, 0, 2)) {
90+
return $path;
91+
}
92+
93+
if (!$request = $this->requestStack->getMasterRequest()) {
94+
return $path;
95+
}
96+
97+
return $request->getRelativeUriForPath($path);
98+
}
99+
100+
/**
101+
* Returns the name of the extension.
102+
*
103+
* @return string The extension name
104+
*/
105+
public function getName()
106+
{
107+
return 'request';
108+
}
109+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bridge\Twig\Tests\Extension;
13+
14+
use Symfony\Bridge\Twig\Extension\HttpFoundationExtension;
15+
use Symfony\Component\HttpFoundation\RequestStack;
16+
use Symfony\Component\HttpFoundation\Request;
17+
18+
class HttpFoundationExtensionTest extends \PHPUnit_Framework_TestCase
19+
{
20+
/**
21+
* @dataProvider getGenerateAbsoluteUrlData()
22+
*/
23+
public function testGenerateAbsoluteUrl($expected, $path, $pathinfo)
24+
{
25+
$stack = new RequestStack();
26+
$stack->push(Request::create($pathinfo));
27+
$extension = new HttpFoundationExtension($stack);
28+
29+
$this->assertEquals($expected, $extension->generateAbsoluteUrl($path));
30+
}
31+
32+
public function getGenerateAbsoluteUrlData()
33+
{
34+
return array(
35+
array('http://localhost/foo.png', '/foo.png', '/foo/bar.html'),
36+
array('http://localhost/foo/foo.png', 'foo.png', '/foo/bar.html'),
37+
array('http://localhost/foo/foo.png', 'foo.png', '/foo/bar'),
38+
array('http://localhost/foo/bar/foo.png', 'foo.png', '/foo/bar/'),
39+
40+
array('http://example.com/baz', 'http://example.com/baz', '/'),
41+
array('https://example.com/baz', 'https://example.com/baz', '/'),
42+
array('//example.com/baz', '//example.com/baz', '/'),
43+
);
44+
}
45+
46+
/**
47+
* @dataProvider getGenerateRelativePathData()
48+
*/
49+
public function testGenerateRelativePath($expected, $path, $pathinfo)
50+
{
51+
if (!method_exists('Symfony\Component\HttpFoundation\Request', 'getRelativeUriForPath')) {
52+
$this->markTestSkipped('Your version of Symfony HttpFoundation is too old.');
53+
}
54+
55+
$stack = new RequestStack();
56+
$stack->push(Request::create($pathinfo));
57+
$extension = new HttpFoundationExtension($stack);
58+
59+
$this->assertEquals($expected, $extension->generateRelativePath($path));
60+
}
61+
62+
public function getGenerateRelativePathData()
63+
{
64+
return array(
65+
array('../foo.png', '/foo.png', '/foo/bar.html'),
66+
array('../baz/foo.png', '/baz/foo.png', '/foo/bar.html'),
67+
array('baz/foo.png', 'baz/foo.png', '/foo/bar.html'),
68+
69+
array('http://example.com/baz', 'http://example.com/baz', '/'),
70+
array('https://example.com/baz', 'https://example.com/baz', '/'),
71+
array('//example.com/baz', '//example.com/baz', '/'),
72+
);
73+
}
74+
}

src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,5 +42,9 @@ public function process(ContainerBuilder $container)
4242
if ($container->has('fragment.handler')) {
4343
$container->getDefinition('twig.extension.httpkernel')->addTag('twig.extension');
4444
}
45+
46+
if ($container->has('request_stack')) {
47+
$container->getDefinition('twig.extension.httpfoundation')->addTag('twig.extension');
48+
}
4549
}
4650
}

src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@
103103
<argument type="service" id="fragment.handler" />
104104
</service>
105105

106+
<service id="twig.extension.httpfoundation" class="Symfony\Bridge\Twig\Extension\HttpFoundationExtension" public="false">
107+
<argument type="service" id="request_stack" />
108+
</service>
106109

107110
<service id="twig.extension.form" class="%twig.extension.form.class%" public="false">
108111
<argument type="service" id="twig.form.renderer" />

src/Symfony/Component/HttpFoundation/Request.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,6 +1137,61 @@ public function getUriForPath($path)
11371137
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
11381138
}
11391139

1140+
/**
1141+
* Returns the path as relative reference from the current Request path.
1142+
*
1143+
* Only the URIs path component (no schema, host etc.) is relevant and must be given.
1144+
* Both paths must be absolute and not contain relative parts.
1145+
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
1146+
* Furthermore, they can be used to reduce the link size in documents.
1147+
*
1148+
* Example target paths, given a base path of "/a/b/c/d":
1149+
* - "/a/b/c/d" -> ""
1150+
* - "/a/b/c/" -> "./"
1151+
* - "/a/b/" -> "../"
1152+
* - "/a/b/c/other" -> "other"
1153+
* - "/a/x/y" -> "../../x/y"
1154+
*
1155+
* @param string $path The target path
1156+
*
1157+
* @return string The relative target path
1158+
*/
1159+
public function getRelativeUriForPath($path)
1160+
{
1161+
// be sure that we are dealing with an absolute path
1162+
if (!isset($path[0]) || '/' !== $path[0]) {
1163+
return $path;
1164+
}
1165+
1166+
if ($path === $basePath = $this->getPathInfo()) {
1167+
return '';
1168+
}
1169+
1170+
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
1171+
$targetDirs = explode('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path);
1172+
array_pop($sourceDirs);
1173+
$targetFile = array_pop($targetDirs);
1174+
1175+
foreach ($sourceDirs as $i => $dir) {
1176+
if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
1177+
unset($sourceDirs[$i], $targetDirs[$i]);
1178+
} else {
1179+
break;
1180+
}
1181+
}
1182+
1183+
$targetDirs[] = $targetFile;
1184+
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
1185+
1186+
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
1187+
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
1188+
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name
1189+
// (see http://tools.ietf.org/html/rfc3986#section-4.2).
1190+
return !isset($path[0]) || '/' === $path[0]
1191+
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
1192+
? "./$path" : $path;
1193+
}
1194+
11401195
/**
11411196
* Generates the normalized query string for the Request.
11421197
*

src/Symfony/Component/HttpFoundation/Tests/RequestTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,26 @@ public function testGetUriForPath()
575575
$this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'));
576576
}
577577

578+
/**
579+
* @dataProvider getRelativeUriForPathData()
580+
*/
581+
public function testGetRelativeUriForPath($expected, $pathinfo, $path)
582+
{
583+
$this->assertEquals($expected, Request::create($pathinfo)->getRelativeUriForPath($path));
584+
}
585+
586+
public function getRelativeUriForPathData()
587+
{
588+
return array(
589+
array('me.png', '/foo', '/me.png'),
590+
array('../me.png', '/foo/bar', '/me.png'),
591+
array('me.png', '/foo/bar', '/foo/me.png'),
592+
array('../baz/me.png', '/foo/bar/b', '/foo/baz/me.png'),
593+
array('../../fooz/baz/me.png', '/foo/bar/b', '/fooz/baz/me.png'),
594+
array('baz/me.png', '/foo/bar/b', 'baz/me.png'),
595+
);
596+
}
597+
578598
/**
579599
* @covers Symfony\Component\HttpFoundation\Request::getUserInfo
580600
*/

0 commit comments

Comments
 (0)
0