Skip to content

Commit

Permalink
feature #49913 [TwigBridge][TwigBundle] Add current locale to `AppVar…
Browse files Browse the repository at this point in the history
…iable` (SVillette)

This PR was squashed before being merged into the 6.3 branch.

Discussion
----------

[TwigBridge][TwigBundle] Add current locale to `AppVariable`

| Q             | A
| ------------- | ---
| Branch?       | 6.3
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       | Fix #49870
| License       | MIT
| Doc PR        | symfony/symfony-docs#18190

As stated in #49870, they were no way to get the current locale without passing it through a variable when rendering a template within `LocaleSwitcher::runWithLocale()`.

```php
#[AsController]
final class HomeController
{
    #[Route('/', name: 'app_home')]
    public function __invoke(LocaleSwitcher $localeSwitcher, Environment $twig): Response
    {
        $localeSwitcher->setLocale('en');

        return $localeSwitcher->runWithLocale('fr', function () use ($twig) {
            return new Response($twig->render('index.html.twig'));
        });
    }
}
```

```twig
{{ app.locale }} // fr
```

A doc PR will be submitted if this change is accepted.

Commits
-------

2371216 [TwigBridge][TwigBundle] Add current locale to `AppVariable`
  • Loading branch information
fabpot committed Apr 11, 2023
2 parents 6cd8bd0 + 2371216 commit 6b92f5d
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/Symfony/Bridge/Twig/AppVariable.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Translation\LocaleSwitcher;

/**
* Exposes some Symfony parameters and services as an "app" global variable.
Expand All @@ -29,6 +30,7 @@ class AppVariable
private RequestStack $requestStack;
private string $environment;
private bool $debug;
private LocaleSwitcher $localeSwitcher;

/**
* @return void
Expand Down Expand Up @@ -62,6 +64,11 @@ public function setDebug(bool $debug)
$this->debug = $debug;
}

public function setLocaleSwitcher(LocaleSwitcher $localeSwitcher): void
{
$this->localeSwitcher = $localeSwitcher;
}

/**
* Returns the current token.
*
Expand Down Expand Up @@ -139,6 +146,15 @@ public function getDebug(): bool
return $this->debug;
}

public function getLocale(): string
{
if (!isset($this->localeSwitcher)) {
throw new \RuntimeException('The "app.locale" variable is not available.');
}

return $this->localeSwitcher->getLocale();
}

/**
* Returns some or all the existing flash messages:
* * getFlashes() returns all the flash messages
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.3
---

* Add `AppVariable::getLocale()` to retrieve the current locale when using the `LocaleSwitcher`

6.2
---

Expand Down
18 changes: 18 additions & 0 deletions src/Symfony/Bridge/Twig/Tests/AppVariableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Translation\LocaleSwitcher;

class AppVariableTest extends TestCase
{
Expand Down Expand Up @@ -104,6 +105,16 @@ public function testGetUser()
$this->assertEquals($user, $this->appVariable->getUser());
}

public function testGetLocale()
{
$localeSwitcher = $this->createMock(LocaleSwitcher::class);
$this->appVariable->setLocaleSwitcher($localeSwitcher);

$localeSwitcher->method('getLocale')->willReturn('fr');

self::assertEquals('fr', $this->appVariable->getLocale());
}

public function testGetTokenWithNoToken()
{
$tokenStorage = $this->createMock(TokenStorageInterface::class);
Expand Down Expand Up @@ -156,6 +167,13 @@ public function testGetSessionWithRequestStackNotSet()
$this->appVariable->getSession();
}

public function testGetLocaleWithLocaleSwitcherNotSet()
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('The "app.locale" variable is not available.');
$this->appVariable->getLocale();
}

public function testGetFlashesWithNoRequest()
{
$this->setRequestStack(null);
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Twig/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"symfony/polyfill-intl-icu": "~1.0",
"symfony/property-info": "^5.4|^6.0",
"symfony/routing": "^5.4|^6.0",
"symfony/translation": "^5.4|^6.0",
"symfony/translation": "^6.1",
"symfony/yaml": "^5.4|^6.0",
"symfony/security-acl": "^2.8|^3.0",
"symfony/security-core": "^5.4|^6.0",
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/TwigBundle/Resources/config/twig.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
->call('setDebug', [param('kernel.debug')])
->call('setTokenStorage', [service('security.token_storage')->ignoreOnInvalid()])
->call('setRequestStack', [service('request_stack')->ignoreOnInvalid()])
->call('setLocaleSwitcher', [service('translation.locale_switcher')->ignoreOnInvalid()])

->set('twig.template_iterator', TemplateIterator::class)
->args([service('kernel'), abstract_arg('Twig paths'), param('twig.default_path'), abstract_arg('File name pattern')])
Expand Down

0 comments on commit 6b92f5d

Please sign in to comment.