Completed
Push — master ( f2324b...cefc4c )
by Daniel
49s
created

DateTimeType::configureOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
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']);
0 ignored issues
show
Security Bug introduced by
It seems like $formatter->format($data) targeting Symfony\Component\Intl\D...DateFormatter::format() can also be of type false; however, Psi\Component\ContentTyp...TimeView::__construct() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
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