DateTimeFormatterExtension   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 50
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getFilters() 0 6 1
A format() 0 15 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Marek\SiteAccessAwareDateFormatBundle\Twig\Extension;
6
7
use DateTimeInterface;
8
use Marek\SiteAccessAwareDateFormatBundle\Core\SiteAccessAwareFormatter;
9
use Twig\Extension\AbstractExtension;
10
use Twig\TwigFilter;
11
use Twig\Environment;
12
use Twig\Extension\CoreExtension;
13
14
final class DateTimeFormatterExtension extends AbstractExtension
15
{
16
    /**
17
     * @var \Marek\SiteAccessAwareDateFormatBundle\Core\SiteAccessAwareFormatter
18
     */
19
    protected $formatter;
20
21
    /**
22
     * DateTimeFormatterExtension constructor.
23
     *
24
     * @param \Marek\SiteAccessAwareDateFormatBundle\Core\SiteAccessAwareFormatter $formatter
25
     */
26
    public function __construct(SiteAccessAwareFormatter $formatter)
27
    {
28
        $this->formatter = $formatter;
29
    }
30
31
    public function getFilters(): array
32
    {
33
        return [
34
            new TwigFilter('m_datetime', [$this, 'format'], ['needs_environment' => true]),
35
        ];
36
    }
37
38
    /**
39
     * Calls date formatter.
40
     *
41
     * @param \Twig\Environment $environment
42
     * @param \DateTimeInterface $date
43
     * @param string $format
44
     * @param string|null $timezone
45
     *
46
     * @return string
47
     */
48
    public function format(Environment $environment, DateTimeInterface $date, $format = 'default', $timezone = null): string
49
    {
50
        if (null === $timezone) {
51
            $timezone = $environment->getExtension(CoreExtension::class)->getTimezone();
52
        } elseif (!$timezone instanceof \DateTimeZone) {
53
            $timezone = new \DateTimeZone($timezone);
54
        }
55
56
        $date = clone $date;
57
        if (false !== $timezone) {
58
            $date->setTimezone($timezone);
59
        }
60
61
        return $this->formatter->format($date, $format);
62
    }
63
}
64