DateTimeFormatter::filter()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace JhFlexiTime\Filter;
4
5
use Zend\Filter\DateTimeFormatter as ZfDateTimeFormatter;
6
use JhFlexiTime\DateTime\DateTime;
7
8
/**
9
 * Class DateTimeFormatter
10
 * @package JhFlexiTime\Filter
11
 * @author Aydin Hassan <[email protected]>
12
 */
13
class DateTimeFormatter extends ZfDateTimeFormatter
14
{
15
16
    /**
17
     * Filter a datetime string by normalizing it to the filters specified format
18
     *
19
     * @param  string $value
20
     * @return string
21
     */
22
    public function filter($value)
23
    {
24
        try {
25
            $result = $this->normalizeDateTime($value);
26
        } catch (\Exception $e) {
27
            // DateTime threw an exception, an invalid date string was provided
28
            //just return original input - this is what other filters do
29
            return $value;
30
        }
31
32
        return $result;
33
    }
34
35
    /**
36
     * Return a DateTime object
37
     *
38
     * @param  string|int|DateTime $value
39
     * @return string
40
     */
41
    protected function normalizeDateTime($value)
42
    {
43
        if ($value === '' || $value === null) {
44
            return $value;
45
        } elseif (is_int($value)) {
46
            $value = new DateTime('@' . $value);
47
        } elseif (!$value instanceof DateTime) {
48
            $value = new DateTime($value);
49
        }
50
51
        return $value;
52
    }
53
}
54