1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Psi\Component\ContentType\Standard\View; |
6
|
|
|
|
7
|
|
|
use Psi\Component\ContentType\View\TypeInterface; |
8
|
|
|
use Psi\Component\ContentType\View\ViewFactory; |
9
|
|
|
use Psi\Component\ContentType\View\ViewInterface; |
10
|
|
|
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; |
11
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
12
|
|
|
|
13
|
|
|
class DateTimeType implements TypeInterface |
14
|
|
|
{ |
15
|
|
|
private static $acceptedFormats = [ |
16
|
|
|
'full' => \IntlDateFormatter::FULL, |
17
|
|
|
'long' => \IntlDateFormatter::LONG, |
18
|
|
|
'medium' => \IntlDateFormatter::MEDIUM, |
19
|
|
|
'short' => \IntlDateFormatter::SHORT, |
20
|
|
|
'none' => \IntlDateFormatter::NONE, |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
|
public function createView(ViewFactory $factory, $data, array $options): ViewInterface |
24
|
|
|
{ |
25
|
|
|
$dateFormat = $this->resolveFormat($options['date_format']); |
26
|
|
|
$timeFormat = $this->resolveFormat($options['time_format']); |
27
|
|
|
|
28
|
|
|
$formatter = new \IntlDateFormatter( |
29
|
|
|
\Locale::getDefault(), |
30
|
|
|
$dateFormat, |
31
|
|
|
$timeFormat, |
32
|
|
|
null, |
33
|
|
|
\IntlDateFormatter::GREGORIAN |
34
|
|
|
); |
35
|
|
|
|
36
|
|
|
return new DateTimeView($formatter->format($data), $data, $options['tag']); |
|
|
|
|
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function configureOptions(OptionsResolver $options) |
40
|
|
|
{ |
41
|
|
|
$options->setDefaults([ |
42
|
|
|
'tag' => null, |
43
|
|
|
'date_format' => \IntlDateFormatter::MEDIUM, |
44
|
|
|
'time_format' => \IntlDateFormatter::MEDIUM, |
45
|
|
|
]); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private function resolveFormat($format) |
49
|
|
|
{ |
50
|
|
|
if (is_int($format)) { |
51
|
|
|
if (in_array($format, self::$acceptedFormats)) { |
52
|
|
|
return $format; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$format = strtolower($format); |
57
|
|
|
if (!isset(self::$acceptedFormats[$format])) { |
58
|
|
|
throw new InvalidOptionsException(sprintf( |
59
|
|
|
'Invalid format "%s". It must either be one of the \IntlDateFormatter constant values or one of the following strings: "%s"', |
60
|
|
|
$format, implode('", "', array_keys(self::$acceptedFormats)) |
61
|
|
|
)); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return self::$acceptedFormats[$format]; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|