DateType::convertToModlrValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace As3\Modlr\DataTypes\Types;
4
5
use \DateTime;
6
7
/**
8
 * The date data type converter.
9
 *
10
 * @author Jacob Bare <[email protected]>
11
 */
12
class DateType implements TypeInterface
13
{
14
    /**
15
     * {@inheritDoc}
16
     */
17
    public function convertToModlrValue($value)
18
    {
19
        if (null === $value) {
20
            return null;
21
        }
22
        return $this->createDateTime($value);
23
    }
24
25
    /**
26
     * Creates a DateTime object based on a value.
27
     *
28
     * @param   mixed   $value
29
     * @return  DateTime
30
     */
31
    private function createDateTime($value)
32
    {
33
        if ($value instanceof DateTime) {
34
            return $value;
35
        }
36
        if ($value instanceof \MongoDate) {
37
            $dateStr = date('Y-m-d H:i:s.'.$value->usec, $value->sec);
38
            return new DateTime($dateStr);
39
        }
40
        if (is_numeric($value)) {
41
            // Supports microseconds
42
            $value = (Float) $value;
43
            $usec = round(($value - (Integer) $value) * 1000000, 0);
44
            $dateStr = date('Y-m-d H:i:s.'.$usec, (Integer) $value);
45
            return new DateTime($dateStr);
46
        }
47
        return new DateTime((String) $value);
48
    }
49
}
50