<?php
namespace Hona\AdminBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\EntityManager;
use Doctrine\DBAL\Types\Type;
use Hona\AdminBundle\DoctrineDBALTypes\UTCDateTimeType;
use Hona\AdminBundle\Library\Utils;
use Hona\AdminBundle\Entity\User;
use Hona\AdminBundle\Security\AdminUser;
use Symfony\Component\DependencyInjection\Container;
class TimezoneListener
{
/**
*
* @param TokenStorageInterface $token_storage
* @param EntityManager $em
* @param \Twig_Environment $twig
* @param Container $container
*/
public function __construct(TokenStorageInterface $token_storage, \Twig_Environment $twig, Container $container)
{
$this->token_storage = $token_storage;
$this->twig = $twig;
$this->container = $container;
}
/**
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$token = $this->token_storage->getToken();
if ($token != null && $token->getUser() instanceof AdminUser) {
// override doctrine datetime class
Type::overrideType('datetime', UTCDateTimeType::class);
Type::overrideType('datetimetz', UTCDateTimeType::class);
//check for user timezone
// set time zone
if (!defined('_USER_TIMEZONE_')) {
define('_USER_TIMEZONE_', Utils::getParameter('default_timezone'));
}
// get utc time zone offset
$now = new \DateTime();
$mins = $now->getOffset() / 60;
$sgn = ($mins < 0 ? -1 : 1);
$mins = abs($mins);
$hrs = floor($mins / 60);
$mins -= $hrs * 60;
$offset = sprintf('%+d:%02d', $hrs * $sgn, $mins);
$this->twig->addGlobal('TIMEZONE_UTC', $offset);
}else{
if (!defined('_USER_TIMEZONE_')) {
define('_USER_TIMEZONE_', 'UTC');
}
}
date_default_timezone_set(_USER_TIMEZONE_);
}
}