Skip to content

Deprecate the global variables in Twig in favor of Twig functions #13356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ public function getFunctions()
return array(
new \Twig_SimpleFunction('absolute_url', array($this, 'generateAbsoluteUrl')),
new \Twig_SimpleFunction('relative_path', array($this, 'generateRelativePath')),
new \Twig_SimpleFunction('request', array($this, 'getRequest')),
new \Twig_SimpleFunction('session', array($this, 'getSession')),
);
}

Expand Down Expand Up @@ -97,6 +99,28 @@ public function generateRelativePath($path)
return $request->getRelativeUriForPath($path);
}

/**
* Returns the current request.
*
* @return Request|null The HTTP request object
*/
public function getRequest()
{
return $this->requestStack->getCurrentRequest();
}

/**
* Returns the current session.
*
* @return Session|null The session
*/
public function getSession()
{
if ($request = $this->getRequest()) {
return $request->getSession();
}
}

/**
* Returns the name of the extension.
*
Expand Down
60 changes: 60 additions & 0 deletions src/Symfony/Bridge/Twig/Extension/KernelExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?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;

/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class KernelExtension extends \Twig_Extension
{
private $environment;
private $debug;

public function __construct($environment, $debug)
{
$this->environment = $environment;
$this->debug = $debug;
}

public function getFunctions()
{
return array(
new \Twig_SimpleFunction('is_debug', array($this, 'isDebug')),
new \Twig_SimpleFunction('env', array($this, 'getEnvironment')),
);
}

/**
* Returns the current app environment.
*
* @return string The current environment string (e.g 'dev')
*/
public function getEnvironment()
{
return $this->environment;
}

/**
* Returns the current debug flag.
*
* @return bool Whether debug is enabled or not
*/
public function isDebug()
{
return $this->debug;
}

public function getName()
{
return 'kernel';
}
}
40 changes: 30 additions & 10 deletions src/Symfony/Bridge/Twig/Extension/SecurityExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
* SecurityExtension exposes security context features.
Expand All @@ -22,18 +24,27 @@
class SecurityExtension extends \Twig_Extension
{
private $securityChecker;
private $tokenStorage;

public function __construct(AuthorizationCheckerInterface $securityChecker = null)
public function __construct(AuthorizationCheckerInterface $securityChecker, TokenStorageInterface $tokenStorage)
{
$this->securityChecker = $securityChecker;
$this->tokenStorage = $tokenStorage;
}

public function isGranted($role, $object = null, $field = null)
/**
* {@inheritdoc}
*/
public function getFunctions()
{
if (null === $this->securityChecker) {
return false;
}
return array(
new \Twig_SimpleFunction('is_granted', array($this, 'isGranted')),
new \Twig_SimpleFunction('user', array($this, 'getUser')),
);
}

public function isGranted($role, $object = null, $field = null)
{
if (null !== $field) {
$object = new FieldVote($object, $field);
}
Expand All @@ -42,13 +53,22 @@ public function isGranted($role, $object = null, $field = null)
}

/**
* {@inheritdoc}
* Returns the current user.
*
* @return mixed
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

object|null actually

*
* @see TokenInterface::getUser()
*/
public function getFunctions()
public function getUser()
{
return array(
new \Twig_SimpleFunction('is_granted', array($this, 'isGranted')),
);
if (!$token = $this->tokenStorage->getToken()) {
return;
}

$user = $token->getUser();
if (is_object($user)) {
return $user;
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,24 @@ public function getGenerateRelativePathData()
array('//example.com/baz', '//example.com/baz', '/'),
);
}

public function testGetRequest()
{
$stack = new RequestStack();
$stack->push($request = Request::create('/'));
$extension = new HttpFoundationExtension($stack);

$this->assertSame($request, $extension->getRequest());
}

public function testGetSession()
{
$stack = new RequestStack();
$stack->push($request = Request::create('/'));
$extension = new HttpFoundationExtension($stack);

$request->setSession($this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface'));

$this->assertSame($request->getSession(), $extension->getSession());
}
}
24 changes: 24 additions & 0 deletions src/Symfony/Bridge/Twig/Tests/Extension/KernelExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?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\KernelExtension;

class KernelExtensionTest extends \PHPUnit_Framework_TestCase
{
public function test()
{
$extension = new KernelExtension('foo', true);
$this->assertTrue($extension->isDebug());
$this->assertEquals('foo', $extension->getEnvironment());
}
}
67 changes: 67 additions & 0 deletions src/Symfony/Bridge/Twig/Tests/Extension/SecurityExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?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\SecurityExtension;

class SecurityExtensionTest extends \PHPUnit_Framework_TestCase
{
public function testIsGranted()
{
$checker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$checker->expects($this->once())->method('isGranted')->will($this->returnValue(true));
$storage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');

$extension = new SecurityExtension($checker, $storage);
$this->assertTrue($extension->isGranted('ROLE_ADMIN'));
}

public function testGetUserWithoutToken()
{
$checker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
$storage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');
$storage->expects($this->once())->method('getToken')->will($this->returnValue(null));

$extension = new SecurityExtension($checker, $storage);
$this->assertNull($extension->getUser());
}

public function testGetUserWithNullUser()
{
$checker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');

$token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$token->expects($this->once())->method('getUser')->will($this->returnValue(null));

$storage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');
$storage->expects($this->once())->method('getToken')->will($this->returnValue($token));

$extension = new SecurityExtension($checker, $storage);
$this->assertNull($extension->getUser());
}

public function testGetUserWithUser()
{
$checker = $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');

$user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');

$token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
$token->expects($this->once())->method('getUser')->will($this->returnValue($user));

$storage = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');
$storage->expects($this->once())->method('getToken')->will($this->returnValue($token));

$extension = new SecurityExtension($checker, $storage);
$this->assertSame($user, $extension->getUser());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@

<service id="twig.extension.security" class="%twig.extension.security.class%" public="false">
<tag name="twig.extension" />
<argument type="service" id="security.authorization_checker" on-invalid="ignore" />
<argument type="service" id="security.authorization_checker" />
<argument type="service" id="security.token_storage" />
</service>
</services>
</container>
12 changes: 12 additions & 0 deletions src/Symfony/Bundle/TwigBundle/AppVariable.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
* Exposes some Symfony parameters and services as an "app" global variable.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since version 2.7, to be removed in 3.0. Use request(), user(), env(), session(), is_debug() instead.
*/
class AppVariable
{
Expand Down Expand Up @@ -86,6 +88,8 @@ public function getSecurity()
*/
public function getUser()
{
trigger_error('The "app.user" variable is deprecated since version 2.7 and will be removed in 3.0. Use the user() function instead.', E_USER_DEPRECATED);

if (null === $this->tokenStorage) {
throw new \RuntimeException('The "app.user" variable is not available.');
}
Expand All @@ -107,6 +111,8 @@ public function getUser()
*/
public function getRequest()
{
trigger_error('The "app.request" variable is deprecated since version 2.7 and will be removed in 3.0. Use the request() function instead.', E_USER_DEPRECATED);

if (null === $this->requestStack) {
throw new \RuntimeException('The "app.request" variable is not available.');
}
Expand All @@ -121,6 +127,8 @@ public function getRequest()
*/
public function getSession()
{
trigger_error('The "app.session" variable is deprecated since version 2.7 and will be removed in 3.0. Use the session() function instead.', E_USER_DEPRECATED);

if (null === $this->requestStack) {
throw new \RuntimeException('The "app.session" variable is not available.');
}
Expand All @@ -137,6 +145,8 @@ public function getSession()
*/
public function getEnvironment()
{
trigger_error('The "app.environment" variable is deprecated since version 2.7 and will be removed in 3.0. Use the env() function instead.', E_USER_DEPRECATED);

if (null === $this->environment) {
throw new \RuntimeException('The "app.environment" variable is not available.');
}
Expand All @@ -151,6 +161,8 @@ public function getEnvironment()
*/
public function getDebug()
{
trigger_error('The "app.debug" variable is deprecated since version 2.7 and will be removed in 3.0. Use the is_debug() function instead.', E_USER_DEPRECATED);

if (null === $this->debug) {
throw new \RuntimeException('The "app.debug" variable is not available.');
}
Expand Down
6 changes: 6 additions & 0 deletions src/Symfony/Bundle/TwigBundle/Resources/config/twig.xml
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@
<argument type="service" id="twig.form.renderer" />
</service>

<service id="twig.extension.kernel" class="Symfony\Bridge\Twig\Extension\KernelExtension" public="false">
<tag name="twig.extension" />
<argument>%kernel.environment%</argument>
<argument>%kernel.debug%</argument>
</service>

<service id="twig.form.engine" class="%twig.form.engine.class%" public="false">
<argument>%twig.form.resources%</argument>
</service>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ public function test()
$kernel->boot();

$container = $kernel->getContainer();

$content = $container->get('twig')->render('index.html.twig');
$this->assertContains('{ a: b }', $content);
$this->assertContains('Debug: 1', $content);
$this->assertContains('Env: dev', $content);
}

protected function setUp()
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
{{ {a: 'b'}|yaml_encode }}
Debug: {{ is_debug() }}
Env: {{ env() }}