TimeExtension   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 10
c 2
b 1
f 0
lcom 1
cbo 3
dl 0
loc 58
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getName() 0 4 1
A getFunctions() 0 6 1
C diff() 0 31 7
1
<?php
2
3
namespace AppBundle\Twig;
4
5
use Symfony\Component\Translation\TranslatorInterface;
6
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)
17
    {
18
        $this->translator = $translator;
19
    }
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()
61
    {
62
        return 'time';
63
    }
64
}
65