Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added a FilterLocaleSwitchEvent to handle the persisting of locales i…

…n the cookie / session.

Updated Docs
Remove the event dispatcher from the controller, since it is not used anymore
Moved the response vary header to listener
  • Loading branch information...
commit 02ccf05f0733126dc9a41fc0dc52de9c85a7ebad 1 parent 2d2f8b5
@lunetics authored
View
14 Controller/LocaleController.php
@@ -12,6 +12,7 @@
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
+
use Lunetics\LocaleBundle\Validator\MetaValidator;
/**
@@ -22,10 +23,10 @@
*/
class LocaleController
{
- protected $router;
- protected $useReferrer;
- protected $redirectToRoute;
- protected $metaValidator;
+ private $router;
+ private $metaValidator;
+ private $useReferrer;
+ private $redirectToRoute;
/**
* @param RouterInterface $router Router Service
@@ -61,10 +62,6 @@ public function switchAction(Request $request)
if (!$metaValidator->isAllowed($_locale)) {
throw new \InvalidArgumentException(sprintf('Not allowed to switch to locale %s', $_locale));
}
- // Save into session
- // TODO: Build Locale Persister and decouple from the guessers
- $session = $request->getSession();
- $session->set('lunetics_locale', $_locale);
// Redirect the User
if ($this->useReferrer && $request->headers->has('referer')) {
@@ -76,7 +73,6 @@ public function switchAction(Request $request)
// TODO: also it doesn't handle the locale at all and can therefore lead to an infinite redirect
$response = new RedirectResponse($request->getScheme() . '://' . $request->getHttpHost() . '/', $statusCode);
}
- $response->setVary('accept-language');
return $response;
View
17 Cookie/LocaleCookie.php
@@ -22,10 +22,9 @@ class LocaleCookie
private $domain;
private $secure;
private $httpOnly;
- private $setOnDetection;
- private $setOnSwitch;
+ private $setOnChange;
- public function __construct($name, $ttl, $path, $domain = null, $secure, $httpOnly, $setOnDetection, $setOnSwitch)
+ public function __construct($name, $ttl, $path, $domain = null, $secure, $httpOnly, $setOnChange)
{
$this->name = $name;
$this->ttl = $ttl;
@@ -33,8 +32,7 @@ public function __construct($name, $ttl, $path, $domain = null, $secure, $httpOn
$this->domain = $domain;
$this->secure = $secure;
$this->httpOnly = $httpOnly;
- $this->setOnDetection = $setOnDetection;
- $this->setOnSwitch = $setOnSwitch;
+ $this->setOnChange = $setOnChange;
}
public function getLocaleCookie($locale)
@@ -46,14 +44,9 @@ public function getLocaleCookie($locale)
return $cookie;
}
- public function setCookieOnDetection()
+ public function setCookieOnChange()
{
- return $this->setOnDetection;
- }
-
- public function setCookieOnSwitch()
- {
- return $this->setOnSwitch;
+ return $this->setOnChange;
}
private function computeExpireTime()
View
3  DependencyInjection/Configuration.php
@@ -86,8 +86,7 @@ public function getConfigTreeBuilder()
->arrayNode('cookie')
->addDefaultsIfNotSet()
->children()
- ->scalarNode('set_on_detection')->defaultFalse()->end()
- ->scalarNode('set_on_switch')->defaultTrue()->end()
+ ->scalarNode('set_on_change')->defaultTrue()->end()
->scalarNode('class')->defaultValue('Lunetics\LocaleBundle\Cookie\LocaleCookie')->end()
->scalarNode('name')->defaultValue('lunetics_locale')->end()
->scalarNode('ttl')->defaultValue('86400')->end()
View
49 Event/FilterLocaleSwitchEvent.php
@@ -0,0 +1,49 @@
+<?php
+/**
+ * This file is part of the LuneticsLocaleBundle package.
+ *
+ * <https://github.com/lunetics/LocaleBundle/>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that is distributed with this source code.
+ */
+namespace Lunetics\LocaleBundle\Event;
+
+use Symfony\Component\EventDispatcher\Event;
+
+/**
+ * Filter for the LocaleSwitchEvent
+ */
+class FilterLocaleSwitchEvent extends Event
+{
+ /**
+ * @var string
+ */
+ protected $locale;
+
+ /**
+ * Constructor
+ *
+ * @param string $locale
+ *
+ * @throws \InvalidArgumentException
+ */
+ public function __construct($locale)
+ {
+ if (!is_string($locale) || null == $locale || '' == $locale) {
+ throw new \InvalidArgumentException(sprintf('Wrong type, expected \'string\' got \'%s\'', $locale));
+ }
+
+ $this->locale = $locale;
+ }
+
+ /**
+ * Returns the locale string
+ *
+ * @return string
+ */
+ public function getLocale()
+ {
+ return $this->locale;
+ }
+}
View
77 EventListener/LocaleListener.php
@@ -11,12 +11,14 @@
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
-use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\HttpKernel\KernelEvents;
+use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
-use Symfony\Component\EventDispatcher\Event;
+use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
+
use Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserManager;
-use Lunetics\LocaleBundle\Cookie\LocaleCookie;
+use Lunetics\LocaleBundle\Event\FilterLocaleSwitchEvent;
+use Lunetics\LocaleBundle\LocaleBundleEvents;
/**
* Locale Listener
@@ -47,29 +49,17 @@ class LocaleListener
private $dispatcher;
/**
- * @var LocaleCookie
- */
- private $localeCookie;
-
- /**
- * @var string
- */
- private $identifiedLocale;
-
- /**
* Construct the guessermanager
*
* @param string $defaultLocale Framework default locale
* @param LocaleGuesserManager $guesserManager Locale Guesser Manager
- * @param LocaleCookie $localeCookie Locale Cookie
* @param LoggerInterface $logger Logger
*/
- public function __construct($defaultLocale = 'en', LocaleGuesserManager $guesserManager, LocaleCookie $localeCookie, LoggerInterface $logger = null)
+ public function __construct($defaultLocale = 'en', LocaleGuesserManager $guesserManager, LoggerInterface $logger = null)
{
$this->defaultLocale = $defaultLocale;
$this->guesserManager = $guesserManager;
$this->logger = $logger;
- $this->localeCookie = $localeCookie;
}
/**
@@ -95,29 +85,18 @@ public function onKernelRequest(GetResponseEvent $event)
$manager = $this->guesserManager;
- if ($result = $manager->runLocaleGuessing($request)) {
- $guesser = $result['guesser'];
- $locale = $result['locale'];
+ if ($locale = $manager->runLocaleGuessing($request)) {
$this->logEvent('Setting [ %s ] as defaultLocale for the Request', $locale);
$request->setLocale($locale);
- $this->identifiedLocale = $locale;
-
- $forceSet = in_array($guesser, array('query'));
-
- if ($forceSet) {
- $this->logEvent('Force setting [ %s ]', $locale);
- }
- if (in_array('cookie', $manager->getGuessingOrder())) {
- if ($this->localeCookie->setCookieOnDetection() && !$request->cookies->has($this->localeCookie->getName()) || $forceSet) {
- $this->addCookieResponseListener();
- }
- }
- if (in_array('session', $manager->getGuessingOrder())) {
- /** @var $session \Lunetics\LocaleBundle\LocaleGuesser\SessionLocaleGuesser */
- $session = $manager->getGuesser('session');
- $session->setSessionLocale($this->identifiedLocale, $forceSet);
+ if ($manager->getGuesser('session') || $manager->getGuesser('cookie')) {
+ $localeSwitchEvent = new FilterLocaleSwitchEvent($locale);
+ $this->dispatcher->dispatch(LocaleBundleEvents::onLocaleChange, $localeSwitchEvent);
}
+ $this->dispatcher->addListener(KernelEvents::RESPONSE, function(FilterResponseEvent $event) {
+ return $event->getResponse()->setVary('Accept-Language');
+ });
+
return;
}
$request->setDefaultLocale($this->defaultLocale);
@@ -134,34 +113,6 @@ public function setEventDispatcher(EventDispatcher $dispatcher)
}
/**
- * Method to add the ResponseListener which sets the cookie. Should only be called once
- */
- public function addCookieResponseListener()
- {
- $this->dispatcher->addListener(
- KernelEvents::RESPONSE,
- array($this, 'onResponse')
- );
- }
-
- /**
- * Called at the kernel.response event to attach the cookie to the request
- *
- * @param Event $event
- *
- * @return \Symfony\Component\HttpFoundation\Response;
- */
- public function onResponse(Event $event)
- {
- $response = $event->getResponse();
- $cookie = $this->localeCookie->getLocaleCookie($this->identifiedLocale);
- $response->headers->setCookie($cookie);
- $this->logEvent('Locale Cookie set to [ %s ]', $this->identifiedLocale);
-
- return $response;
- }
-
- /**
* Log detection events
*
* @param string $logMessage
View
161 EventListener/LocaleUpdateListener.php
@@ -0,0 +1,161 @@
+<?php
+/**
+ * This file is part of the LuneticsLocaleBundle package.
+ *
+ * <https://github.com/lunetics/LocaleBundle/>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that is distributed with this source code.
+ */
+namespace Lunetics\LocaleBundle\EventListener;
+
+use Symfony\Component\HttpKernel\HttpKernelInterface;
+use Symfony\Component\HttpKernel\Log\LoggerInterface;
+use Symfony\Component\HttpKernel\KernelEvents;
+use Symfony\Component\EventDispatcher\EventDispatcher;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
+
+use Lunetics\LocaleBundle\Cookie\LocaleCookie;
+use Lunetics\LocaleBundle\Event\FilterLocaleSwitchEvent;
+use Lunetics\LocaleBundle\Session\LocaleSession;
+
+/**
+ * Locale Update Listener
+ *
+ * @author Matthias Breddin <mb@lunetics.com>
+ */
+class LocaleUpdateListener
+{
+ /**
+ * @var string
+ */
+ private $locale;
+ /**
+ * @var LocaleSession
+ */
+ private $session;
+ /**
+ * @var LocaleCookie
+ */
+ private $localeCookie;
+
+ /**
+ * @var Request
+ */
+ private $request;
+
+ /**
+ * @var array
+ */
+ private $registeredGuessers;
+
+ /**
+ * @var LoggerInterface
+ */
+ private $logger;
+
+ /**
+ * Construct the Locale Update Listener
+ *
+ * @param LocaleCookie $localeCookie Locale Cookie
+ * @param LocaleSession $session Locale Session
+ * @param Request $request Request
+ * @param EventDispatcher $dispatcher Event Dispatcher
+ * @param array $registeredGuessers List of registered guessers
+ * @param LoggerInterface $logger Logger
+ */
+ public function __construct(LocaleCookie $localeCookie,
+ LocaleSession $session,
+ Request $request,
+ EventDispatcher $dispatcher,
+ $registeredGuessers = array(),
+ LoggerInterface $logger = null)
+ {
+ $this->localeCookie = $localeCookie;
+ $this->session = $session;
+ $this->request = $request;
+ $this->dispatcher = $dispatcher;
+ $this->logger = $logger;
+ $this->registeredGuessers = $registeredGuessers;
+ }
+
+ /**
+ * Processes the locale updates. Adds listener for the cookie and updates the session.
+ *
+ * @param FilterLocaleSwitchEvent $event
+ */
+ public function onLocaleChange(FilterLocaleSwitchEvent $event)
+ {
+ $this->locale = $event->getLocale();
+ $this->updateCookie($this->localeCookie->setCookieOnChange());
+ $this->updateSession();
+ }
+
+ /**
+ * Update Cookie Section
+ *
+ * @param bool $update If cookie should be updated
+ */
+ public function updateCookie($update)
+ {
+ if ($this->checkGuesser('cookie')
+ && $update === true
+ && $this->request->cookies->get($this->localeCookie->getName()) !== $this->locale
+ ) {
+ $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'updateCookieOnResponse'));
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Event for updating the cookie on response
+ *
+ * @param FilterResponseEvent $event
+ *
+ * @return \Symfony\Component\HttpFoundation\Response;
+ */
+ public function updateCookieOnResponse(FilterResponseEvent $event)
+ {
+ $response = $event->getResponse();
+ $cookie = $this->localeCookie->getLocaleCookie($this->locale);
+ $response->headers->setCookie($cookie);
+ if (null !== $this->logger) {
+ $this->logger->info(sprintf('Locale Cookie set to [ %s ]', $this->locale));
+ }
+
+ return $response;
+ }
+
+ /**
+ * Update Session section
+ */
+ public function updateSession()
+ {
+ if ($this->checkGuesser('session') && $this->session->hasLocaleChanged($this->locale)) {
+ if (null !== $this->logger) {
+ $this->logger->info(sprintf('Session var \'%s\' set to [ %s ]', $this->session->getSessionVar(), $this->locale));
+ }
+ $this->session->setLocale($this->locale);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns if a guesser is
+ *
+ * @param string $guesser Name of the guesser to check
+ *
+ * @return bool
+ */
+ private function checkGuesser($guesser)
+ {
+ return in_array($guesser, $this->registeredGuessers);
+ }
+}
View
28 LocaleBundleEvents.php
@@ -0,0 +1,28 @@
+<?php
+/**
+ * This file is part of the LuneticsLocaleBundle package.
+ *
+ * <https://github.com/lunetics/LocaleBundle/>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that is distributed with this source code.
+ */
+namespace Lunetics\LocaleBundle;
+
+/**
+ * Defines aliases for Events in this bundle
+ */
+final class LocaleBundleEvents
+{
+ /**
+ * The lunetics_locale.change event is thrown each time the locale changes.
+ *
+ * The available locales to be chosen can be restricted through the allowed_languages configuration.
+ *
+ * The event listener receives an Lunetics\LocaleBundle\Event\FilterLocaleSwitchEvent instance
+ *
+ * @var string
+ *
+ */
+ const onLocaleChange = 'lunetics_locale.change';
+}
View
17 LocaleGuesser/LocaleGuesserManager.php
@@ -9,11 +9,12 @@
*/
namespace Lunetics\LocaleBundle\LocaleGuesser;
-use Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserInterface;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
+use Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserInterface;
+
/**
* Locale Guesser Manager
*
@@ -80,6 +81,18 @@ public function getGuesser($alias)
}
/**
+ * Removes a guesser from this manager
+ *
+ * @param string $alias
+ *
+ * @return bool
+ */
+ public function removeGuesser($alias)
+ {
+ unset($this->guessers[$alias]);
+ }
+
+ /**
* Loops through all the activated Locale Guessers and
* calls the guessLocale methode and passing the current request.
*
@@ -102,7 +115,7 @@ public function runLocaleGuessing(Request $request)
$locale = $guesserService->getIdentifiedLocale();
$this->logEvent('Locale has been identified by guessing service: ( %s )', ucfirst($guesser));
- return array('guesser' => $guesser, 'locale' => $locale);
+ return $locale;
}
$this->logEvent('Locale has not been identified by the %s guessing service', ucfirst($guesser));
}
View
19 Resources/config/services.xml
@@ -26,19 +26,32 @@
<argument>%lunetics_locale.cookie.domain%</argument>
<argument>%lunetics_locale.cookie.secure%</argument>
<argument>%lunetics_locale.cookie.httpOnly%</argument>
- <argument>%lunetics_locale.cookie.set_on_detection%</argument>
- <argument>%lunetics_locale.cookie.set_on_switch%</argument>
+ <argument>%lunetics_locale.cookie.set_on_change%</argument>
+ </service>
+
+ <service id="lunetics_locale.locale_session" class="Lunetics\LocaleBundle\Session\LocaleSession">
+ <argument type="service" id="session" />
+ <argument>%lunetics_locale.session.variable%</argument>
</service>
<service id="lunetics_locale.locale_listener" class="%lunetics_locale.request_listener.class%">
<argument>%locale%</argument>
<argument type="service" id="lunetics_locale.guesser_manager" />
- <argument type="service" id="lunetics_locale.locale_cookie" />
<argument type="service" id="logger" />
<call method="setEventDispatcher">
<argument type="service" id="event_dispatcher"/>
</call>
<tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest"/>
</service>
+
+ <service id="lunetics_locale.locale_update_listener" class="Lunetics\LocaleBundle\EventListener\LocaleUpdateListener" scope="request">
+ <argument type="service" id="lunetics_locale.locale_cookie" />
+ <argument type="service" id="lunetics_locale.locale_session" />
+ <argument type="service" id="request" />
+ <argument type="service" id="event_dispatcher" />
+ <argument>%lunetics_locale.guessing_order%</argument>
+ <argument type="service" id="logger" />
+ <tag name="kernel.event_listener" event="lunetics_locale.change" method="onLocaleChange" />
+ </service>
</services>
</container>
View
16 Resources/doc/index.markdown
@@ -89,12 +89,12 @@ The session and cookie guesser is usually used when you do not use locales in th
it is good to set *session* and/or *cookie* as the first guesser to not try to detect the locale at each request.
#### Cookie
-You can set a cookie when a locale has been identified, simply activate it in the configuration:
+If you use the cookie guesser, it will be automatically read from the cookie and write changes into the cookie anytime the locale has changed (Even from another guesser)
``` yaml
lunetics_locale:
cookie:
- set_on_detection: true
+ set_on_change: true
```
This is most useful for unregistered and returning visitors.
@@ -102,6 +102,18 @@ This is most useful for unregistered and returning visitors.
The session guesser will automatically save a previously identified locale into the session and retrieve it from the session. This guesser should always be first in your `guessing_order` configuration if you don't use the router guesser.
+### FilterLocaleSwitchEvent / LocaleUpdateListener
+The `LocaleGuesserManager` dispatches a `LocaleBundleEvents::onLocalChange` if you use either the 'session' or `cookie` guesser. The LocaleUpdateListeners checks if the locale has changed and updates the session or cookie.
+
+
+For example, if you don't use route / query parameters for locales, you could build an own listener for your user login, which dispatches a `LocaleBundleEvents::onLocalChange` event to set the locale for your user. You just have to use the `FilterLocaleSwitchEvent` and set the locale.
+
+``` php
+$locale = $user->getLocale();
+$localeSwitchEvent = new FilterLocaleSwitchEvent($locale);
+$this->dispatcher->dispatch(LocaleBundleEvents::onLocaleChange, $localeSwitchEvent);
+```
+
### Custom Guessers
Read more about creating your own guesser here:
View
83 Session/LocaleSession.php
@@ -0,0 +1,83 @@
+<?php
+/**
+ * This file is part of the LuneticsLocaleBundle package.
+ *
+ * <https://github.com/lunetics/LocaleBundle/>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that is distributed with this source code.
+ */
+
+namespace Lunetics\LocaleBundle\Session;
+
+use Symfony\Component\HttpFoundation\Session\Session;
+
+/**
+ * LocaleSessionClass
+ */
+class LocaleSession
+{
+
+ /**
+ * @var Session
+ */
+ private $session;
+ /**
+ * @var string
+ */
+ private $sessionVar;
+
+ /**
+ * Constructor
+ *
+ * @param Session $session Session
+ * @param string $sessionVar Session config var
+ */
+ public function __construct(Session $session, $sessionVar = 'lunetics_locale')
+ {
+ $this->session = $session;
+ $this->sessionVar = $sessionVar;
+ }
+
+ /**
+ * Checks if the locale has changes
+ *
+ * @param string $locale
+ *
+ * @return bool
+ */
+ public function hasLocaleChanged($locale)
+ {
+ return $locale !== $this->session->get($this->sessionVar);
+ }
+
+ /**
+ * Sets the locale
+ *
+ * @param string $locale
+ */
+ public function setLocale($locale)
+ {
+ $this->session->set($this->sessionVar, $locale);
+ }
+
+ /**
+ * Returns the locale
+ *
+ * @param string $locale
+ */
+ public function getLocale($locale)
+ {
+ $this->session->get($this->sessionVar, $locale);
+ }
+
+ /**
+ * Returns the session var/key where the locale is saved in
+ *
+ * @return string
+ */
+ public function getSessionVar()
+ {
+ return $this->sessionVar;
+ }
+}
View
4 Tests/Controller/LocaleControllerTest.php
@@ -10,12 +10,12 @@
namespace Lunetics\LocaleBundle\Tests\Controller;
use Symfony\Component\HttpFoundation\Request;
-use Lunetics\LocaleBundle\Controller\LocaleController;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
+use Lunetics\LocaleBundle\Controller\LocaleController;
-class LocaleCookieTest extends \PHPUnit_Framework_TestCase
+class LocaleControllerTest extends \PHPUnit_Framework_TestCase
{
public function testControllerThrowsException()
{
View
41 Tests/Event/FilterLocaleSwitchEventTest.php
@@ -0,0 +1,41 @@
+<?php
+/**
+ * This file is part of the LuneticsLocaleBundle package.
+ *
+ * <https://github.com/lunetics/LocaleBundle/>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that is distributed with this source code.
+ */
+
+namespace Lunetics\LocaleBundle\Tests\Event;
+
+use Lunetics\LocaleBundle\Event\FilterLocaleSwitchEvent;
+
+class FilterLocaleSwitchEventTest extends \PHPUnit_Framework_TestCase
+{
+ public function testFilterLocaleSwitchEvent()
+ {
+ $locale = 'de';
+ $filter = new FilterLocaleSwitchEvent($locale);
+ $this->assertEquals('de', $filter->getLocale());
+ }
+
+ /**
+ * @dataProvider invalidType
+ */
+ public function testThrowsInvalidTypeException($locale)
+ {
+ $this->setExpectedException('\InvalidArgumentException');
+ new FilterLocaleSwitchEvent($locale);
+ }
+
+ public function invalidType()
+ {
+ return array(
+ array(123),
+ array(''),
+ array(null)
+ );
+ }
+}
View
83 Tests/EventListener/LocaleListenerTest.php
@@ -10,25 +10,27 @@
namespace Lunetics\LocaleBundle\Tests\EventListener;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
+use Symfony\Component\HttpFoundation\Session\Session;
+use Symfony\Component\HttpKernel\HttpKernelInterface;
+use Symfony\Component\HttpKernel\Event\GetResponseEvent;
+
use Lunetics\LocaleBundle\EventListener\LocaleListener;
use Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserManager;
use Lunetics\LocaleBundle\LocaleGuesser\RouterLocaleGuesser;
use Lunetics\LocaleBundle\LocaleGuesser\BrowserLocaleGuesser;
use Lunetics\LocaleBundle\LocaleGuesser\CookieLocaleGuesser;
use Lunetics\LocaleBundle\LocaleGuesser\QueryLocaleGuesser;
-use Lunetics\LocaleBundle\Cookie\LocaleCookie;
use Lunetics\LocaleBundle\Validator\MetaValidator;
-use Symfony\Component\HttpFoundation\Request;
-use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
-use Symfony\Component\HttpFoundation\Session\Session;
-use Symfony\Component\HttpKernel\HttpKernelInterface;
-use Symfony\Component\HttpKernel\Event\GetResponseEvent;
+use Lunetics\LocaleBundle\LocaleBundleEvents;
+
class LocaleListenerTest extends \PHPUnit_Framework_TestCase
{
public function testDefaultLocaleWithoutParams()
{
- $listener = new LocaleListener('fr', $this->getGuesserManager(), $this->getLocaleCookie());
+ $listener = $this->getListener('fr', $this->getGuesserManager());
$request = Request::create('/');
$request->headers->set('Accept-language', '');
$event = $this->getEvent($request);
@@ -39,7 +41,7 @@ public function testDefaultLocaleWithoutParams()
public function testCustomLocaleIsSetWhenParamsExist()
{
- $listener = new LocaleListener('fr', $this->getGuesserManager(), $this->getLocaleCookie());
+ $listener = $this->getListener('fr', $this->getGuesserManager());
$request = Request::create('/', 'GET');
$request->attributes->set('_locale', 'de');
$event = $this->getEvent($request);
@@ -50,7 +52,7 @@ public function testCustomLocaleIsSetWhenParamsExist()
public function testCustomLocaleIsSetWhenQueryExist()
{
- $listener = new LocaleListener('fr', $this->getGuesserManager(array(0 => 'router', 1 => 'query', 2 => 'browser')), $this->getLocaleCookie());
+ $listener = $this->getListener('fr', $this->getGuesserManager(array(0 => 'router', 1 => 'query', 2 => 'browser')));
$request = Request::create('/', 'GET');
$request->query->set('_locale', 'de');
$event = $this->getEvent($request);
@@ -68,7 +70,7 @@ public function testRouteLocaleIsReturnedIfRouterIsPrio1()
{
$request = $this->getFullRequest();
$manager = $this->getGuesserManager();
- $listener = new LocaleListener('en', $manager, $this->getLocaleCookie());
+ $listener = $this->getListener('en', $manager);
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('es', $request->getLocale());
@@ -83,7 +85,7 @@ public function testBrowserLocaleIsReturnedIfBrowserIsPrio1()
{
$request = $this->getFullRequest();
$manager = $this->getGuesserManager(array(1 => 'browser', 2 => 'router'));
- $listener = new LocaleListener('en', $manager, $this->getLocaleCookie());
+ $listener = $this->getListener('en', $manager);
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('fr_FR', $request->getLocale());
@@ -98,27 +100,53 @@ public function testBrowserTakeOverIfRouterParamsFail()
{
$request = $this->getFullRequest(null);
$manager = $this->getGuesserManager();
- $listener = new LocaleListener('en', $manager, $this->getLocaleCookie());
+ $listener = $this->getListener('en', $manager);
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('fr_FR', $request->getLocale());
}
- /**
- * Router is prio 1
- * Request DOES NOT contains _locale parameter in rou$defaultLocale = 'en';ter
- * Request contains browser locale preferences
- */
public function testThatGuesserIsNotCalledIfNotInGuessingOrder()
{
$request = $this->getRequestWithRouterParam();
$manager = $this->getGuesserManager(array(0 => 'browser'));
- $listener = new LocaleListener('en', $manager, $this->getLocaleCookie());
+ $listener = $this->getListener('en', $manager);
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('en', $request->getLocale());
}
+ public function testDispatcherIsFired()
+ {
+ $dispatcherMock = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock();
+ $dispatcherMock->expects($this->once())
+ ->method('dispatch')
+ ->with($this->equalTo(LocaleBundleEvents::onLocaleChange), $this->isInstanceOf('Lunetics\LocaleBundle\Event\FilterLocaleSwitchEvent'));
+
+ $listener = $this->getListener('fr', $this->getGuesserManager());
+ $listener->setEventDispatcher($dispatcherMock);
+
+
+ $event = $this->getEvent($this->getRequestWithRouterParam());
+ $listener->onKernelRequest($event);
+ }
+
+ public function testDispatcherIsNotFired()
+ {
+ $dispatcherMock = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock();
+ $dispatcherMock->expects($this->never())
+ ->method('dispatch');
+
+ $manager = $this->getGuesserManager();
+ $manager->removeGuesser('session');
+ $manager->removeGuesser('cookie');
+ $listener = $this->getListener('fr', $manager);
+ $listener->setEventDispatcher($dispatcherMock);
+
+ $event = $this->getEvent($this->getRequestWithRouterParam());
+ $listener->onKernelRequest($event);
+ }
+
/**
* Request with empty route params and empty browser preferences
*/
@@ -126,7 +154,7 @@ public function testDefaultLocaleIfEmptyRequest()
{
$request = $this->getEmptyRequest();
$manager = $this->getGuesserManager();
- $listener = new LocaleListener('en', $manager, $this->getLocaleCookie());
+ $listener = $this->getListener('en', $manager);
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('en', $request->getLocale());
@@ -137,7 +165,7 @@ public function testAjaxRequestsAreHandled()
$request = $this->getRequestWithRouterParam('fr');
$request->headers->set('X-Requested-With', 'XMLHttpRequest');
$manager = $this->getGuesserManager(array(0 => 'router'));
- $listener = new LocaleListener('en', $manager, $this->getLocaleCookie());
+ $listener = $this->getListener('en', $manager);
$event = $this->getEvent($request);
$listener->onKernelRequest($event);
$this->assertEquals('fr', $request->getLocale());
@@ -148,6 +176,14 @@ private function getEvent(Request $request)
return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST);
}
+ private function getListener($locale, $manager)
+ {
+ $listener = new LocaleListener($locale, $manager);
+ $listener->setEventDispatcher(new \Symfony\Component\EventDispatcher\EventDispatcher());
+
+ return $listener;
+ }
+
private function getGuesserManager($order = array(1 => 'router', 2 => 'browser'))
{
$allowedLocales = array('de', 'fr', 'fr_FR', 'nl', 'es', 'en');
@@ -223,11 +259,4 @@ private function getEmptyRequest()
return $request;
}
-
- private function getLocaleCookie($onDetection = false, $onSwitch = true)
- {
- $cookie = new LocaleCookie('lunetics_locale', 86400, '/', null, false, true, $onDetection, $onSwitch);
-
- return $cookie;
- }
}
View
175 Tests/EventListener/LocaleUpdateTest.php
@@ -0,0 +1,175 @@
+<?php
+/**
+ * This file is part of the LuneticsLocaleBundle package.
+ *
+ * <https://github.com/lunetics/LocaleBundle/>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that is distributed with this source code.
+ */
+
+namespace Lunetics\LocaleBundle\Tests\EventListener;
+
+use Symfony\Component\HttpFoundation\Session\Session;
+use Symfony\Component\HttpKernel\KernelEvents;
+use Symfony\Component\HttpKernel\HttpKernelInterface;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
+use Symfony\Component\EventDispatcher\EventDispatcher;
+use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
+use Symfony\Component\HttpFoundation\Response;
+
+use Lunetics\LocaleBundle\EventListener\LocaleUpdateListener;
+use Lunetics\LocaleBundle\Session\LocaleSession;
+use Lunetics\LocaleBundle\Cookie\LocaleCookie;
+
+class LocaleUpdateTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * @var EventDispatcher
+ */
+ private $dispatcher;
+ /**
+ * @var LocaleSession
+ */
+ private $session;
+
+ public function setUp()
+ {
+ $this->dispatcher = new EventDispatcher();
+ $this->session = new LocaleSession(new Session(new MockArraySessionStorage()));
+ }
+
+ public function testCookieIsNotUpdatedNoGuesser()
+ {
+ $listener = $this->getLocaleUpdateListener(array('session'), false, true);
+
+ $this->assertFalse($listener->updateCookie(true));
+ $this->assertFalse($listener->updateCookie(false));
+
+ $listener->onLocaleChange($this->getFilterLocaleSwitchEvent());
+ $addedListeners = $this->dispatcher->getListeners(KernelEvents::RESPONSE);
+
+ $this->assertSame(array(), $addedListeners);
+ }
+
+ public function testCookieIsNotUpdatedOnSameLocale()
+ {
+ $listener = $this->getLocaleUpdateListener(array('cookie'), true, true);
+ $listener->onLocaleChange($this->getFilterLocaleSwitchEvent('de'));
+ $addedListeners = $this->dispatcher->getListeners(KernelEvents::RESPONSE);
+ $this->assertSame(array(), $addedListeners);
+ }
+
+
+ public function testCookieIsUpdatedOnChange()
+ {
+ $listener = $this->getLocaleUpdateListener(array('cookie'), false, true);
+ $listener->onLocaleChange($this->getFilterLocaleSwitchEvent());
+ $addedListeners = $this->dispatcher->getListeners(KernelEvents::RESPONSE);
+ $this->assertContains('updateCookieOnResponse', $addedListeners[0]);
+ }
+
+ public function testCookieIsNotUpdatedWithFalseSetCookieOnChange()
+ {
+ $listener = $this->getLocaleUpdateListener(array('cookie'), false, false);
+ $listener->onLocaleChange($this->getFilterLocaleSwitchEvent());
+ $addedListeners = $this->dispatcher->getListeners(KernelEvents::RESPONSE);
+ $this->assertSame(array(), $addedListeners);
+ }
+
+ public function testUpdateCookieOnResponse()
+ {
+ $event = $this->getEvent($this->getRequest());
+ $listener = $this->getLocaleUpdateListener();
+
+ $reflectionClass = new \ReflectionClass($listener);
+ $property = $reflectionClass->getProperty('locale');
+ $property->setAccessible(true);
+ $property->setValue($listener, 'es');
+
+ $response = $listener->updateCookieOnResponse($event);
+
+ /** @var $cookie \Symfony\Component\HttpFoundation\Cookie */
+ list($cookie) = $response->headers->getCookies();
+ $this->assertInstanceOf('Symfony\Component\HttpFoundation\Cookie', $cookie);
+ $this->assertEquals('lunetics_locale', $cookie->getName());
+ $this->assertEquals('es', $cookie->getValue());
+
+ }
+
+ public function testUpdateSession()
+ {
+ $this->session->setLocale('el');
+ $listener = $this->getLocaleUpdateListener(array('session'));
+
+ $reflectionClass = new \ReflectionClass($listener);
+ $property = $reflectionClass->getProperty('locale');
+ $property->setAccessible(true);
+ $property->setValue($listener, 'tr');
+
+ $this->assertTrue($listener->updateSession());
+ }
+
+ public function testNotUpdateSessionNoGuesser()
+ {
+ $this->session->setLocale('el');
+ $listener = $this->getLocaleUpdateListener(array('cookie'));
+
+ $reflectionClass = new \ReflectionClass($listener);
+ $property = $reflectionClass->getProperty('locale');
+ $property->setAccessible(true);
+ $property->setValue($listener, 'el');
+
+ $this->assertFalse($listener->updateSession());
+ }
+
+ public function testNotUpdateSessionSameLocale()
+ {
+ $this->session->setLocale('el');
+ $listener = $this->getLocaleUpdateListener(array('session'));
+
+ $reflectionClass = new \ReflectionClass($listener);
+ $property = $reflectionClass->getProperty('locale');
+ $property->setAccessible(true);
+ $property->setValue($listener, 'el');
+
+ $this->assertFalse($listener->updateSession());
+ }
+
+ private function getFilterLocaleSwitchEvent($locale = 'fr')
+ {
+ return new \Lunetics\LocaleBundle\Event\FilterLocaleSwitchEvent($locale);
+ }
+
+ private function getLocaleUpdateListener($registeredGuessers = array(), $withCookieSet = true, $updateCookie = false)
+ {
+ $listener = new LocaleUpdateListener($this->getLocaleCookie($updateCookie),
+ $this->session,
+ $this->getRequest($withCookieSet),
+ $this->dispatcher,
+ $registeredGuessers);
+
+ return $listener;
+ }
+
+ private function getEvent(Request $request)
+ {
+ return new FilterResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST, new Response);
+ }
+
+
+ private function getLocaleCookie($updateCookie)
+ {
+ $cookie = new LocaleCookie('lunetics_locale', 86400, '/', null, false, true, $updateCookie);
+
+ return $cookie;
+ }
+
+ private function getRequest($withCookieSet = false)
+ {
+ $request = Request::create('/', 'GET', array(), $withCookieSet ? array('lunetics_locale' => 'de') : array());
+
+ return $request;
+ }
+}
View
7 Tests/LocaleGuesser/LocaleGuesserManagerTest.php
@@ -9,11 +9,12 @@
*/
namespace Lunetics\LocaleBundle\Tests\LocaleGuesser;
+use Symfony\Component\HttpFoundation\Request;
+
use Lunetics\LocaleBundle\LocaleGuesser\RouterLocaleGuesser;
use Lunetics\LocaleBundle\LocaleGuesser\QueryLocaleGuesser;
use Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserManager;
use Lunetics\LocaleBundle\LocaleGuesser\LocaleGuesserInterface;
-use Symfony\Component\HttpFoundation\Request;
use Lunetics\LocaleBundle\Validator\MetaValidator;
class LocaleGuesserManagerTest extends \PHPUnit_Framework_TestCase
@@ -46,8 +47,8 @@ public function testLocaleIsIdentifiedByTheQueryGuessingService()
->method('guessLocale')
->will($this->returnValue(false));
$manager->addGuesser($guesserMock, 'browser');
- $guessing = $manager->runLocaleGuessing($request);
- $this->assertEquals('fr', $guessing['locale']);
+ $locale = $manager->runLocaleGuessing($request);
+ $this->assertEquals('fr', $locale);
}
public function testLocaleIsNotIdentifiedIfNoQueryParamsExist()
Please sign in to comment.
Something went wrong with that request. Please try again.