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
|
|
|
|