| 1 | <?php | ||
| 7 | class TimeExtension extends \Twig_Extension | ||
| 8 | { | ||
| 9 | protected $translator; | ||
| 10 | |||
| 11 | /** | ||
| 12 | * Constructor | ||
| 13 | * | ||
| 14 | * @param TranslatorInterface $translator Translator used for messages | ||
| 15 | */ | ||
| 16 | public function __construct(TranslatorInterface $translator) | ||
| 20 | |||
| 21 | public function getFunctions() | ||
| 22 |     { | ||
| 23 | return [ | ||
| 24 |             new \Twig_SimpleFunction('time_diff', [$this, 'diff'], ['is_safe' => ['html']]) | ||
| 25 | ]; | ||
| 26 | } | ||
| 27 | |||
| 28 | public function diff($since = null, $to = null) | ||
| 29 |     { | ||
| 30 |         foreach (['since', 'to'] as $var) { | ||
| 31 |             if ($$var instanceof \DateTime) { | ||
| 32 | continue; | ||
| 33 | } | ||
| 34 |             if (is_integer($$var)) { | ||
| 35 |                 $$var = date('Y-m-d H:i:s', $$var); | ||
| 36 | } | ||
| 37 | $$var = new \DateTime($$var); | ||
| 38 | } | ||
| 39 | |||
| 40 | static $units = [ | ||
| 41 | 'y' => 'year', | ||
| 42 | 'm' => 'month', | ||
| 43 | 'd' => 'day', | ||
| 44 | 'h' => 'hour', | ||
| 45 | 'i' => 'minute', | ||
| 46 | 's' => 'second' | ||
| 47 | ]; | ||
| 48 | |||
| 49 | $diff = $to->diff($since); | ||
| 50 |         foreach ($units as $attr => $unit) { | ||
| 51 |             $count = $diff->{$attr}; | ||
| 52 |             if (0 !== $count) { | ||
| 53 |                 $id = sprintf('%s.%s', $diff->invert ? 'ago' : 'in', $unit); | ||
| 54 | return $this->translator->transChoice($id, $count, ['%count%' => $count], 'time'); | ||
| 55 | } | ||
| 56 | } | ||
| 57 |         return $this->translator->trans('empty', [], 'time'); | ||
| 58 | } | ||
| 59 | |||
| 60 | public function getName() | ||
| 64 | } | ||
| 65 |