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