Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Symfony 2.6+ User Timezone
...
twig:
...
date:
timezone: America/Los_Angeles
services:
am_user.user_subscriber:
class: AppBundle\EventListener\UserSubscriber
arguments: [@fos_user.user_manager]
tags:
- { name: kernel.event_subscriber }
common.twig.subscriber:
class: AppBundle\EventListener\TwigSubscriber
arguments: [@twig,@security.token_storage]
tags:
- { name: kernel.event_subscriber }
<?php
namespace AppBundle\EventListener;
use AppBundle\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Thanks @jwrobeson for guidance.
* @see http://mindimize.com/viewpage/3987/symfony-2-timezone-solutions-handle-user-timezone-on-symfony
*/
class TwigSubscriber implements EventSubscriberInterface
{
protected $twig;
protected $tokenStorage;
function __construct(\Twig_Environment $twig, TokenStorageInterface $tokenStorage)
{
$this->twig = $twig;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
'kernel.controller' => 'onKernelController'
];
}
public function onKernelController(FilterControllerEvent $event)
{
$token = $this->tokenStorage->getToken();
if ($token !== null) {
$user = $token->getUser();
if ($user instanceof User) {
$timezone = $user->getTimezone();
if ($timezone !== null) {
$this->twig->getExtension('core')->setTimezone($timezone);
}
}
}
}
}
<?php
namespace AppBundle\EventListener;
use AppBundle\Entity\User;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* @see http://mindimize.com/viewpage/3987/symfony-2-timezone-solutions-handle-user-timezone-on-symfony
*/
class UserSubscriber implements EventSubscriberInterface
{
private $userManager;
public function __construct(UserManagerInterface $userManager)
{
$this->userManager = $userManager;
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
];
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof User) {
//here, you can do whatever you want after user login successfully: send mail, set last login, set your timezone, ...
//this is timezone you can detect or you define
$request = $event->getRequest();
$timezoneDetect = $request->request->get('_timezone_detect');
if ($timezoneDetect != null) {
$user->setTimezone($timezoneDetect);
$this->userManager->updateUser($user);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment