Skip to content

Commit

Permalink
feature #13264 URL manipulations as a Twig extension (fabpot)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
fabpot committed Jan 10, 2015
2 parents 5d56459 + 8fa9050 commit d2657ec
Show file tree
Hide file tree
Showing 3 changed files with 188 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

2.7.0
-----

* added an HttpFoundation extension (provides the `absolute_url` and the `relative_path` functions)

2.5.0
-----

Expand Down
109 changes: 109 additions & 0 deletions Extension/HttpFoundationExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Extension;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Request;

/**
* Twig extension for the Symfony HttpFoundation component.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class HttpFoundationExtension extends \Twig_Extension
{
private $requestStack;

public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}

/**
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('absolute_url', array($this, 'generateAbsoluteUrl')),
new \Twig_SimpleFunction('relative_path', array($this, 'generateRelativePath')),
);
}

/**
* Returns the absolute URL for the given absolute or relative path.
*
* This method returns the path unchanged if no request is available.
*
* @param string $path The path
*
* @return string The absolute URL
*
* @see Request::getUriForPath()
*/
public function generateAbsoluteUrl($path)
{
if (false !== strpos($path, '://') || '//' === substr($path, 0, 2)) {
return $path;
}

if (!$request = $this->requestStack->getMasterRequest()) {
return $path;
}

if (!$path || '/' !== $path[0]) {
$prefix = $request->getPathInfo();
$last = strlen($prefix) - 1;
if ($last !== $pos = strrpos($prefix, '/')) {
$prefix = substr($prefix, 0, $pos).'/';
}

$path = $prefix.$path;
}

return $request->getUriForPath($path);
}

/**
* Returns a relative path based on the current Request.
*
* This method returns the path unchanged if no request is available.
*
* @param string $path The path
*
* @return string The relative path
*
* @see Request::getRelativeUriForPath()
*/
public function generateRelativePath($path)
{
if (false !== strpos($path, '://') || '//' === substr($path, 0, 2)) {
return $path;
}

if (!$request = $this->requestStack->getMasterRequest()) {
return $path;
}

return $request->getRelativeUriForPath($path);
}

/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'request';
}
}
74 changes: 74 additions & 0 deletions Tests/Extension/HttpFoundationExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\HttpFoundationExtension;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Request;

class HttpFoundationExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider getGenerateAbsoluteUrlData()
*/
public function testGenerateAbsoluteUrl($expected, $path, $pathinfo)
{
$stack = new RequestStack();
$stack->push(Request::create($pathinfo));
$extension = new HttpFoundationExtension($stack);

$this->assertEquals($expected, $extension->generateAbsoluteUrl($path));
}

public function getGenerateAbsoluteUrlData()
{
return array(
array('http://localhost/foo.png', '/foo.png', '/foo/bar.html'),
array('http://localhost/foo/foo.png', 'foo.png', '/foo/bar.html'),
array('http://localhost/foo/foo.png', 'foo.png', '/foo/bar'),
array('http://localhost/foo/bar/foo.png', 'foo.png', '/foo/bar/'),

array('http://example.com/baz', 'http://example.com/baz', '/'),
array('https://example.com/baz', 'https://example.com/baz', '/'),
array('//example.com/baz', '//example.com/baz', '/'),
);
}

/**
* @dataProvider getGenerateRelativePathData()
*/
public function testGenerateRelativePath($expected, $path, $pathinfo)
{
if (!method_exists('Symfony\Component\HttpFoundation\Request', 'getRelativeUriForPath')) {
$this->markTestSkipped('Your version of Symfony HttpFoundation is too old.');
}

$stack = new RequestStack();
$stack->push(Request::create($pathinfo));
$extension = new HttpFoundationExtension($stack);

$this->assertEquals($expected, $extension->generateRelativePath($path));
}

public function getGenerateRelativePathData()
{
return array(
array('../foo.png', '/foo.png', '/foo/bar.html'),
array('../baz/foo.png', '/baz/foo.png', '/foo/bar.html'),
array('baz/foo.png', 'baz/foo.png', '/foo/bar.html'),

array('http://example.com/baz', 'http://example.com/baz', '/'),
array('https://example.com/baz', 'https://example.com/baz', '/'),
array('//example.com/baz', '//example.com/baz', '/'),
);
}
}

0 comments on commit d2657ec

Please sign in to comment.