Created
April 10, 2016 12:13
-
-
Save chrisguitarguy/92bd4517403db7ab9e33498ce62ca8a1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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