1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace GeekLab\GLPDO2\Bindings\MySQL; |
4
|
|
|
|
5
|
|
|
use \PDO; |
6
|
|
|
use \DomainException; |
7
|
|
|
use \Exception; |
8
|
|
|
use GeekLab\GLPDO2\Constants; |
9
|
|
|
use GeekLab\GLPDO2\Bindings\DateTimeBindingInterface; |
10
|
|
|
|
11
|
|
|
class MySQLDateTimeBindings implements DateTimeBindingInterface, Constants |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Bind a date value as date or optional NULL. |
15
|
|
|
* YYYY-MM-DD is the proper date format. |
16
|
|
|
* |
17
|
|
|
* @param string|null $value |
18
|
|
|
* @param bool $null |
19
|
|
|
* |
20
|
|
|
* @return array |
21
|
|
|
* @throws Exception |
22
|
|
|
*/ |
23
|
|
|
public function bDate(?string $value, bool $null = false): array |
24
|
|
|
{ |
25
|
|
|
if ($value === null && !$null) { |
26
|
|
|
throw new DomainException('Can not bind NULL in date spot.'); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
if (empty($value) && $null) { |
30
|
|
|
return [null, PDO::PARAM_NULL]; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
if (!empty($value)) { |
34
|
|
|
$value = trim($value); |
35
|
|
|
return [preg_match(self::DATE_REGEX, $value) ? $value : '1970-01-01', PDO::PARAM_STR]; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return ['1970-01-01', PDO::PARAM_STR]; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Bind a date value as date time or optional NULL. |
43
|
|
|
* YYYY-MM-DD HH:MM:SS is the proper date format. |
44
|
|
|
* |
45
|
|
|
* @param string|null $value |
46
|
|
|
* @param bool $null |
47
|
|
|
* |
48
|
|
|
* @return array |
49
|
|
|
* @throws Exception |
50
|
|
|
*/ |
51
|
|
|
public function bDateTime($value = null, bool $null = false): array |
52
|
|
|
{ |
53
|
|
|
if ($value === null && !$null) { |
54
|
|
|
throw new DomainException('Can not bind NULL in date time spot.'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$dt = 0; |
58
|
|
|
|
59
|
|
|
if ($value !== null) { |
60
|
|
|
// Trim $value and see if it matches full date time string format. |
61
|
|
|
$dt = preg_match(self::DATE_TIME_REGEX, trim($value)); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// Use NULL? |
65
|
|
|
if ($dt === 0 && $null) { |
66
|
|
|
return [null, PDO::PARAM_NULL]; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
if ($dt === 0 && $value !== null) { |
70
|
|
|
if (preg_match(self::DATE_REGEX, $value) === 0) { |
71
|
|
|
// $value is not a valid date string, set to earliest date time available (GMT). |
72
|
|
|
$value = '1970-01-01 00:00:00'; |
73
|
|
|
} else { |
74
|
|
|
// $value is a valid date string, add midnight time. |
75
|
|
|
$value .= ' 00:00:00'; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
// DateTimes are really strings. |
80
|
|
|
return [$value, PDO::PARAM_STR]; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|