Test Failed
Push — develop ( eabf9f )
by Kenneth
03:54
created

MySQLDateTimeBindings::bDateTimeNullable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace GeekLab\GLPDO2\Bindings\MySQL;
4
5
use \PDO;
6
use \InvalidArgumentException;
7
use GeekLab\GLPDO2\Constants;
8
use GeekLab\GLPDO2\Bindings\DateTimeBindingInterface;
9
10
class MySQLDateTimeBindings implements DateTimeBindingInterface, Constants
11
{
12
    /**
13
     * Bind a date value as date or null.
14
     * YYYY-MM-DD is the proper date format.
15
     *
16
     * @param string|null $value
17
     *
18
     * @return array
19
     */
20
    public function bDateNullable(?string $value = null): array
21
    {
22
        if ($value === null) {
23
            return [null, PDO::PARAM_NULL];
24
        }
25
26
        return $this->bDate($value);
27
    }
28
29
    /**
30
     * Bind a date value as date.
31
     * YYYY-MM-DD is the proper date format.
32
     *
33
     * @todo Use PHP's date stuff for validation?
34
     *
35
     * @param string $value
36
     *
37
     * @return array
38
     */
39
    public function bDate(string $value): array
40
    {
41
        $value = trim($value);
42
        return [preg_match(self::DATE_REGEX, $value) ? $value : '1970-01-01', PDO::PARAM_STR];
43
    }
44
45
    /**
46
     * Bind a date value as date time or null.
47
     * YYYY-MM-DD HH:MM:SS is the proper date format.
48
     *
49
     * @param string|null $value
50
     *
51
     * @return array
52
     */
53
    public function bDateTimeNullable(?string $value = null): array
54
    {
55
        if ($value === null) {
56
            return [null, PDO::PARAM_NULL];
57
        }
58
59
        return $this->bDateTime($value);
60
    }
61
62
    /**
63
     * Bind a date value as date time.
64
     * YYYY-MM-DD HH:MM:SS is the proper date time format.
65
     *
66
     * @todo Use PHP's date stuff for validation?
67
     *
68
     * @param string $value
69
     *
70
     * @return array
71
     */
72
    public function bDateTime(string $value): array
73
    {
74
        $value = trim($value);
75
        $isDateTime = preg_match(self::DATE_TIME_REGEX, trim($value));
76
77
78
        if ($isDateTime === 0) {
79
            // $value is not a valid date string, set to earliest date time available (GMT).
80
            // Or $value is a valid date string, add midnight time.
81
            $value = preg_match(self::DATE_REGEX, $value) === 0 ? '1970-01-01 00:00:00' : $value . ' 00:00:00';
82
        }
83
84
        // DateTimes are really strings.
85
        return [$value, PDO::PARAM_STR];
86
    }
87
}
88