Skip to content

Instantly share code, notes, and snippets.

@richard-wm
Forked from Dattaya/10.parameters.ini
Created May 28, 2014 15:57
Show Gist options
  • Select an option

  • Save richard-wm/2ccb47f2289eec5af0d2 to your computer and use it in GitHub Desktop.

Select an option

Save richard-wm/2ccb47f2289eec5af0d2 to your computer and use it in GitHub Desktop.
# symfony2/app/config/parameters.ini
locale="undefined"
fallback_locale="en"
framework:
...
translator: { fallback: %fallback_locale% }
session:
default_locale: %locale%
<?php
// symfony2/src/Application/Sonata/UserBundle/Entity/User.php
class User extends BaseUser
{
//...
/**
* @ORM\Column(name="locale", type="string", length=5, nullable="true")
*
*/
protected $locale;
public function getLocale()
{
return $this->locale;
}
/**
* @param string $locale
*/
public function setLocale($locale)
{
$this->locale = $locale;
}
}
# symfony2/src/Application/Sonata/UserBundle/Resources/config/services.yml
services:
application_sonata_user.security.interactive_login_listener:
class: Application\Sonata\UserBundle\EventListener\UserListener
tags:
- { name: kernel.event_listener, event: security.interactive_login, method: setLocaleForAuthenticatedUser }
application_sonata_user.security.kernel_request_listener:
class: Application\Sonata\UserBundle\EventListener\UserListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: setLocaleForUnauthenticatedUser }
<?php
// symfony2/src/Application/Sonata/UserBundle/EventListener/UserListener.php
namespace Application\Sonata\UserBundle\EventListener;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent,
Symfony\Component\HttpKernel\Event\GetResponseEvent,
Symfony\Component\HttpKernel\HttpKernelInterface;
class UserListener
{
/**
* kernel.request event. If a guest user doesn't have an opened session, locale is equal to
* "undefined" as configured by default in parameters.ini. If so, set as a locale the user's
* preferred language.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
*/
public function setLocaleForUnauthenticatedUser(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
if ('undefined' == $request->getLocale()) {
$request->setLocale($request->getPreferredLanguage());
}
}
/**
* security.interactive_login event. If a user chose a locale in preferences, it would be set,
* if not, a locale that was set by setLocaleForUnauthenticatedUser remains.
*
* @param \Symfony\Component\Security\Http\Event\InteractiveLoginEvent $event
*/
public function setLocaleForAuthenticatedUser(InteractiveLoginEvent $event)
{
/** @var \Application\Sonata\UserBundle\Entity\User $user */
$user = $event->getAuthenticationToken()->getUser();
if ($user->getLocale()) {
$event->getRequest()->setLocale($user->getLocale());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment