<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Twig\Environment;
class TimezoneListener
{
protected $tokenStorage;
protected $container;
private $twig;
public function __construct(TokenStorageInterface $tokenStorage, Environment $twig, ContainerInterface $container)
{
$this->tokenStorage = $tokenStorage;
$this->container = $container;
$this->twig = $twig;
}
/**
*
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event) {
if (!$event->isMainRequest()) {
// don't do anything if it's not the master request
return;
}
$token = $this->tokenStorage->getToken();
// set time zone
if (!defined('_USER_TIMEZONE_')) {
$hasTimezone = 0;
if ($token != null && (($user = $token->getUser()) instanceof \App\Entity\User)) {
//echo 'fine';exit;
$companyTimezone = $this->getUserTimeZone();
$hasTimezone = 1;
}
if($hasTimezone == 1)
define('_USER_TIMEZONE_', $companyTimezone['timezone']);
else
define('_USER_TIMEZONE_', $this->container->getParameter('default_timezone'));
}
date_default_timezone_set(_USER_TIMEZONE_);
$this->twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone(_USER_TIMEZONE_);
}
public function getUserTimeZone($crmId = NULL)
{
$em = $this->container->get('doctrine')->getManager();
if ($crmId == NULL) {
$user = $this->tokenStorage->getToken()->getUser();
$crmId = $user->getActiveCrm();
}
$userCompany = $em->getRepository(\App\Entity\UserCrms::class)->find($crmId);
if ($userCompany instanceof \App\Entity\UserCrms) {
$timeZone = $em->getRepository(\App\Entity\UserTimezone::class)->find($userCompany->getTimezoneId());
if ($timeZone instanceof \App\Entity\UserTimezone) {
$arr = array(
'timezone' => $timeZone->getTimezone(),
'offset' => '(' . $timeZone->getUtcOffset() . ')',
'title' => $timeZone->getTitle()
);
return $arr;
}
}
$arr = array(
'timezone' => 'Australia/Sydney',
'offset' => '(UTC/GMT +11:00)',
'title' => 'Australia/Sydney'
);
return $arr;
}
}