Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created April 10, 2016 12:13
Show Gist options
  • Select an option

  • Save chrisguitarguy/92bd4517403db7ab9e33498ce62ca8a1 to your computer and use it in GitHub Desktop.

Select an option

Save chrisguitarguy/92bd4517403db7ab9e33498ce62ca8a1 to your computer and use it in GitHub Desktop.
<?php
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Acme\Example\Auth\AppUser;
/**
* Replaces the `date` filter with one that uses the user's timezone if a
* user is present.
*/
final class TimeZoneExtension extends \Twig_Extension
{
/**
* @var TokenStorageInterface
*/
private $security;
public function __construct(TokenStorageInterface $security)
{
$this->security = $security;
}
/**
* {@inheritdoc}
*/
public function getFilters()
{
return [
new \Twig_SimpleFilter('date', [$this, 'formatDate'], [
'needs_environment' => true,
]),
];
}
public function formatDate(\Twig_Environment $env, $date, $format=null, $timezone=null)
{
if (null === $timezone) {
$timezone = $this->getUserTimezone();
}
return \twig_date_format_filter($env, $date, $format, $timezone);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'storeroom_tz';
}
private function getUserTimezone()
{
$token = $this->security->getToken();
if ($token && ($user = $token->getUser()) && $user instanceof AppUser) {
return $user->getTimeZone();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment