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
|
|
|
} |
30
|
|
|
|
31
|
1 |
|
public function convertToSQL($value) |
32
|
|
|
{ |
33
|
1 |
|
if ($value === null || $value === '') { |
34
|
|
|
return null; |
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
if (!is_numeric($value)) { |
38
|
|
|
throw new UnexpectedValueException("expected integer value, got: " . gettype($value)); |
39
|
|
|
} |
40
|
|
|
|
41
|
1 |
|
$timestamp = (int) $value; |
42
|
|
|
|
43
|
1 |
|
if ($timestamp === 0) { |
44
|
|
|
throw new UnexpectedValueException("unable to convert value to int: " . $value); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @var DateTime $datetime |
49
|
|
|
*/ |
50
|
1 |
|
$datetime = DateTime::createFromFormat('U', (string) $timestamp); |
51
|
|
|
|
52
|
1 |
|
$datetime->setTimezone(self::$utc_timezone); |
53
|
|
|
|
54
|
1 |
|
return $datetime->format(static::FORMAT); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
public function convertToPHP($value) |
58
|
|
|
{ |
59
|
1 |
|
if (is_int($value)) { |
60
|
|
|
return $value; // return timestamp as-is |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
if ($value === null) { |
64
|
|
|
return $value; // return NULL value as-is |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
if (!is_string($value)) { |
68
|
|
|
throw new UnexpectedValueException("expected string value, got: " . gettype($value)); |
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
$datetime = DateTime::createFromFormat('!' . static::FORMAT, $value, self::$utc_timezone); |
72
|
|
|
|
73
|
1 |
|
if ($datetime === false) { |
74
|
|
|
throw new UnexpectedValueException("unable to convert value from int: " . $value); |
75
|
|
|
} |
76
|
|
|
|
77
|
1 |
|
return $datetime->getTimestamp(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|