AppDateTimeExtension::getName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Application\Bundle\DefaultBundle\Twig;
4
5
use Sonata\IntlBundle\Twig\Extension\DateTimeExtension;
6
7
/**
8
 * Class AppDateTimeExtension for replace months name to nominative or season.
9
 */
10
class AppDateTimeExtension extends \Twig_Extension
11
{
12
    private $months =
13
        [
14
            'uk' =>
15
                [
16
                    'січня' => ['січень', 'зима'],
17
                    'лютого' => ['лютий', 'зима'],
18
                    'березня' => ['березень', 'весна'],
19
                    'квітня' => ['квітень', 'весна'],
20
                    'травня' => ['травень', 'весна'],
21
                    'червня' => ['червень', 'літо'],
22
                    'липня' => ['липень', 'літо'],
23
                    'серпня' => ['серпень', 'літо'],
24
                    'вересня' => ['вересень', 'осінь'],
25
                    'жовтня' => ['жовтень', 'осінь'],
26
                    'листопада' => ['листопад', 'осінь'],
27
                    'грудня' => ['грудень', 'зима'],
28
                ],
29
                'en' =>
30
                [
31
                    'January' => ['January', 'Winter'],
32
                    'February' => ['February', 'Winter'],
33
                    'March' => ['March', 'Spring'],
34
                    'April' => ['April', 'Spring'],
35
                    'May' => ['May', 'Spring'],
36
                    'June' => ['June', 'Summer'],
37
                    'July' => ['July', 'Summer'],
38
                    'August' => ['August', 'Summer'],
39
                    'September' => ['September', 'Autumn'],
40
                    'October' => ['October', 'Autumn'],
41
                    'November' => ['November', 'Autumn'],
42
                    'December' => ['December', 'Winter'],
43
                ],
44
        ];
45
46
    const YEAR_SEASON_FORMAT = 'S';
47
48
    /** @var DateTimeExtension */
49
    private $intlTwigDateTimeService;
50
51
    /** @var bool */
52
    private $convertToSeason = false;
53
54
    /**
55
     * AppDateTimeExtension constructor.
56
     *
57
     * @param DateTimeExtension $intlTwigDateTimeService
58
     */
59
    public function __construct($intlTwigDateTimeService)
60
    {
61
        $this->intlTwigDateTimeService = $intlTwigDateTimeService;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function getFilters()
68
    {
69
        return [
70
            new \Twig_SimpleFilter('app_format_date', [$this, 'formatDate'], ['is_safe' => ['html']]),
71
            new \Twig_SimpleFilter('app_format_date_day_month', [$this, 'formatDateDayMonth'], ['is_safe' => ['html']]),
72
            new \Twig_SimpleFilter('app_format_date_only', [$this, 'formatDateOnly'], ['is_safe' => ['html']]),
73
            new \Twig_SimpleFilter('app_format_time', [$this, 'formatTime'], ['is_safe' => ['html']]),
74
            new \Twig_SimpleFilter('app_format_time_only', [$this, 'formatTimeOnly'], ['is_safe' => ['html']]),
75
            new \Twig_SimpleFilter('app_format_datetime', [$this, 'formatDatetime'], ['is_safe' => ['html']]),
76
        ];
77
    }
78
79
    /**
80
     * @param \Datetime|string|int $date
81
     * @param string|null          $pattern
82
     * @param string|null          $locale
83
     * @param string|null          $timezone
84
     * @param string|null          $dateType
85
     *
86
     * @return string
87
     */
88
    public function formatDate($date, $pattern = null, $locale = null, $timezone = null, $dateType = null)
89
    {
90
        $pattern = $this->checkConvertToSeason($pattern);
91
92
        $formattedDate = $this->intlTwigDateTimeService->formatDate($date, $pattern, $locale, $timezone, $dateType);
93
        if (null !== $pattern && ('uk' === $locale || $this->convertToSeason)) {
94
            $formattedDate = $this->replaceMonthToNominative($formattedDate, $pattern, $locale);
95
        }
96
97
        return $formattedDate;
98
    }
99
100
    /**
101
     * @param \Datetime|string|int $date
102
     * @param string|null          $pattern
103
     * @param string|null          $locale
104
     * @param string|null          $timezone
105
     * @param string|null          $dateType
106
     *
107
     * @return string
108
     */
109
    public function formatDateOnly($date, $pattern = null, $locale = null, $timezone = null, $dateType = null)
110
    {
111
        if (null !== $pattern) {
112
            $pattern = trim(preg_replace('/[Hm:,]+/', '', $pattern));
113
        }
114
115
        return $this->formatDate($date, $pattern, $locale, $timezone, $dateType);
116
    }
117
118
    /**
119
     * @param \Datetime|string|int $date
120
     * @param string|null          $pattern
121
     * @param string|null          $locale
122
     * @param string|null          $timezone
123
     * @param string|null          $dateType
124
     *
125
     * @return string
126
     */
127
    public function formatDateDayMonth($date, $pattern = null, $locale = null, $timezone = null, $dateType = null)
128
    {
129
        if (null !== $pattern) {
130
            $pattern = trim(preg_replace('/[Hm:,Y]+/', '', $pattern));
131
        }
132
133
        return $this->formatDate($date, $pattern, $locale, $timezone, $dateType);
134
    }
135
136
    /**
137
     * @param \Datetime|string|int $time
138
     * @param string|null          $pattern
139
     * @param string|null          $locale
140
     * @param string|null          $timezone
141
     * @param string|null          $timeType
142
     *
143
     * @return string
144
     */
145
    public function formatTime($time, $pattern = null, $locale = null, $timezone = null, $timeType = null)
146
    {
147
        $pattern = $this->checkConvertToSeason($pattern);
148
149
        $formattedDate = $this->intlTwigDateTimeService->formatTime($time, $pattern, $locale, $timezone, $timeType);
150
        if (null !== $pattern && ('uk' === $locale || $this->convertToSeason)) {
151
            $formattedDate = $this->replaceMonthToNominative($formattedDate, $pattern, $locale);
152
        }
153
154
        return $formattedDate;
155
    }
156
157
    /**
158
     * @param \Datetime|string|int $time
159
     * @param string|null          $pattern
160
     * @param string|null          $locale
161
     * @param string|null          $timezone
162
     * @param string|null          $timeType
163
     *
164
     * @return string
165
     */
166
    public function formatTimeOnly($time, $pattern = null, $locale = null, $timezone = null, $timeType = null)
167
    {
168
        if (null !== $pattern) {
169
            $pattern = 'HH:mm';
170
        }
171
172
        return $this->intlTwigDateTimeService->formatTime($time, $pattern, $locale, $timezone, $timeType);
173
    }
174
175
    /**
176
     * @param \Datetime|string|int $time
177
     * @param string|null          $pattern
178
     * @param string|null          $locale
179
     * @param string|null          $timezone
180
     * @param string|null          $dateType
181
     * @param string|null          $timeType
182
     *
183
     * @return string
184
     */
185
    public function formatDatetime($time, $pattern = null, $locale = null, $timezone = null, $dateType = null, $timeType = null)
186
    {
187
        $pattern = $this->checkConvertToSeason($pattern);
188
189
        $formattedDate = $this->intlTwigDateTimeService->formatDatetime($time, $pattern, $locale, $timezone, $dateType, $timeType);
190
        if (null !== $pattern && ('uk' === $locale || $this->convertToSeason)) {
191
            $formattedDate = $this->replaceMonthToNominative($formattedDate, $pattern, $locale);
192
        }
193
194
        return $formattedDate;
195
    }
196
197
    /**
198
     * {@inheritdoc}
199
     */
200
    public function getName()
201
    {
202
        return 'app_datetime';
203
    }
204
205
    /**
206
     * if $pattern have not day, than do Nominative month name in locale,
207
     * or, if it must be season, than replace month name with season name.
208
     *
209
     * @param string $formattedDate
210
     * @param string $pattern
211
     * @param string $locale
212
     *
213
     * @return mixed
214
     */
215
    private function replaceMonthToNominative($formattedDate, $pattern, $locale)
216
    {
217
        $result = $formattedDate;
218
219
        if (null !== $pattern &&
220
            isset($this->months[$locale]) &&
221
            false === strpos($pattern, 'd') &&
222
            false === strpos($pattern, 'j')
223
        ) {
224
            foreach ($this->months[$locale] as $key => $month) {
225
                if (false !== strpos($formattedDate, $key)) {
226
                    $result = str_replace($key, $month[(int) $this->convertToSeason], $formattedDate);
227
                    break;
228
                }
229
            }
230
        }
231
232
        return $result;
233
    }
234
235
    /**
236
     * Check for YEAR_SEASON_FORMAT in $pattern and replace it for full month name.
237
     *
238
     * @param string|null $pattern
239
     *
240
     * @return mixed
241
     */
242
    private function checkConvertToSeason($pattern)
243
    {
244
        $this->convertToSeason = null !== $pattern ? false !== strpos($pattern, self::YEAR_SEASON_FORMAT) : false;
245
        if ($this->convertToSeason) {
246
            $pattern = str_replace(self::YEAR_SEASON_FORMAT, 'MMMM', $pattern);
247
        }
248
249
        return $pattern;
250
    }
251
}
252