forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatetimeCast.php
More file actions
83 lines (68 loc) · 2.34 KB
/
DatetimeCast.php
File metadata and controls
83 lines (68 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\DataCaster\Cast;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\I18n\Time;
/**
* Class DatetimeCast
*
* (PHP) [Time --> string] --> (DB driver) --> (DB column) datetime
* [ <-- string] <-- (DB driver) <-- (DB column) datetime
*/
class DatetimeCast extends BaseCast
{
public static function get(
mixed $value,
array $params = [],
?object $helper = null,
): Time {
if (! is_string($value)) {
self::invalidTypeValueError($value);
}
if (! $helper instanceof BaseConnection) {
$message = 'The parameter $helper must be BaseConnection.';
throw new InvalidArgumentException($message);
}
/** @see https://www.php.net/manual/en/datetimeimmutable.createfromformat.php#datetimeimmutable.createfromformat.parameters */
$format = self::getDateTimeFormat($params, $helper);
return Time::createFromFormat($format, $value);
}
public static function set(
mixed $value,
array $params = [],
?object $helper = null,
): string {
if (! $value instanceof Time) {
self::invalidTypeValueError($value);
}
if (! $helper instanceof BaseConnection) {
$message = 'The parameter $helper must be BaseConnection.';
throw new InvalidArgumentException($message);
}
$format = self::getDateTimeFormat($params, $helper);
return $value->format($format);
}
/**
* Gets DateTime format from the DB connection.
*
* @param list<string> $params Additional param
*/
protected static function getDateTimeFormat(array $params, BaseConnection $db): string
{
return match ($params[0] ?? '') {
'' => $db->dateFormat['datetime'],
'ms' => $db->dateFormat['datetime-ms'],
'us' => $db->dateFormat['datetime-us'],
default => throw new InvalidArgumentException('Invalid parameter: ' . $params[0]),
};
}
}