Completed
Push — master ( f5e5fb...7d0a28 )
by Rasmus
02:24
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
     * @var DateTimeZone
21
     */
22
    private static $utc_timezone;
23
24 1
    public function __construct()
25
    {
26 1
        if (self::$utc_timezone === null) {
27 1
            self::$utc_timezone = new DateTimeZone('UTC');
28
        }
29 1
    }
30
31 1
    public function convertToSQL($value)
32
    {
33 1
        if ($value === null || $value === '') {
34
            return null;
35
        }
36
37 1
        $timestamp = (int) $value;
38
39 1
        if ($timestamp === 0) {
40
            throw new UnexpectedValueException("unable to convert value to int: " . $value);
41
        }
42
43 1
        $datetime = DateTime::createFromFormat('U', $timestamp, self::$utc_timezone);
44
45 1
        return $datetime->format(static::FORMAT);
46
    }
47
48 1
    public function convertToPHP($value)
49
    {
50 1
        if (is_int($value)) {
51
            return $value; // return timestamp as-is
52
        }
53
54 1
        if ($value === null) {
55
            return $value; // return NULL value as-is
56
        }
57
58 1
        $datetime = DateTime::createFromFormat(static::FORMAT, $value, self::$utc_timezone);
59
60 1
        if ($datetime === false) {
61
            throw new UnexpectedValueException("unable to convert value from int: " . $value);
62
        }
63
64 1
        return $datetime->getTimestamp();
65
    }
66
}
67