/
DoctrineDateTimeRFC.php
89 lines (73 loc) · 2.28 KB
/
DoctrineDateTimeRFC.php
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
84
85
86
87
88
89
<?php
declare(strict_types=1);
namespace DDDStarterPack\Type\Doctrine;
use DDDStarterPack\Type\DateTimeRFC;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeImmutableType;
class DoctrineDateTimeRFC extends DateTimeImmutableType
{
/**
* {@inheritDoc}
*/
public function getSQLDeclaration(array $column, AbstractPlatform $platform): mixed
{
return 'DATETIME(6)';
}
/**
* @psalm-suppress MoreSpecificImplementedParamType
*
* @param null|DateTimeRFC $value
* @param AbstractPlatform $platform
*
* @return null|string
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform): mixed
{
if (is_null($value)) {
return null;
}
if ('UTC' !== $value->getTimezone()->getName()) {
$value = $value->setTimezone(new \DateTimeZone('UTC'));
}
return $value->format(DateTimeRFC::NO_TZ_FORMAT);
}
/**
* @psalm-suppress all
*
* @param null|string $value
* @param AbstractPlatform $platform
*
* @throws \Exception
*
* @return null|DateTimeRFC
*/
public function convertToPHPValue($value, AbstractPlatform $platform): null|DateTimeRFC
{
if (null === $value) {
return $value;
}
$tz = new \DateTimeZone(date_default_timezone_get());
if ($value instanceof \DateTimeInterface) {
if ($tz->getName() !== $value->getTimezone()->getName()) {
$value = $value->setTimezone($tz);
}
$date = \DateTimeImmutable::createFromInterface($value);
return DateTimeRFC::createFrom($date->format(DateTimeRFC::FORMAT));
}
$converted = DateTimeRFC::createFromFormat(
DateTimeRFC::NO_TZ_FORMAT,
$value,
new \DateTimeZone('UTC')
);
if (!$converted) {
throw ConversionException::conversionFailedFormat(
$value,
DateTimeRFC::class,
$platform->getDateTimeFormatString()
);
}
$date = $converted->setTimezone($tz);
return DateTimeRFC::createFrom($date->format(DateTimeRFC::FORMAT));
}
}