Completed
Push — master ( f707f5...a08928 )
by Rasmus
02:27
created

TimestampType::convertToSQL()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.25

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
ccs 6
cts 8
cp 0.75
rs 9.2
cc 4
eloc 8
nc 3
nop 1
crap 4.25
1
<?php
2
3
namespace mindplay\sql\model\types;
4
5
use DateTime;
6
use DateTimeZone;
7
use mindplay\sql\model\schema\Type;
8
use UnexpectedValueException;
9
10
/**
11
 * This class maps an SQL DATETIME value to a Unix timestamp (integer) value in PHP.
12
 *
13
 * It assumes DATETIME values being stored relative to the UTC timezone.
14
 */
15
class TimestampType implements Type
16
{
17
    const FORMAT = 'Y-m-d H:i:s';
18
19
    /**
20
     * @return DateTimeZone
21
     */
22 1
    protected static function getTimeZone()
23
    {
24 1
        static $utc;
25
26 1
        if ($utc === null) {
27 1
            $utc = new DateTimeZone('UTC');
28
        }
29
30 1
        return $utc;
31
    }
32
33 1
    public function convertToSQL($value)
34
    {
35 1
        if ($value === null || $value === '') {
36
            return null;
37
        }
38
39 1
        $timestamp = (int) $value;
40
41 1
        if ($timestamp === 0) {
42
            throw new UnexpectedValueException("unable to convert value to int: " . $value);
43
        }
44
45 1
        $datetime = DateTime::createFromFormat('U', $timestamp, self::getTimeZone());
46
47 1
        return $datetime->format(static::FORMAT);
48
    }
49
50 1
    public function convertToPHP($value)
51
    {
52 1
        if (is_int($value)) {
53
            return $value; // return timestamp as-is
54
        }
55
56 1
        if ($value === null) {
57
            return $value; // return NULL value as-is
58
        }
59
60 1
        $datetime = DateTime::createFromFormat(static::FORMAT, $value, self::getTimeZone());
61
62 1
        if ($datetime === false) {
63
            throw new UnexpectedValueException("unable to convert value from int: " . $value);
64
        }
65
66 1
        return $datetime->getTimestamp();
67
    }
68
}
69