|
2 | 2 |
|
3 | 3 | namespace HMS\Doctrine;
|
4 | 4 |
|
| 5 | +use DateTime; |
| 6 | +use DateTimeZone; |
5 | 7 | use Carbon\Carbon;
|
| 8 | +use InvalidArgumentException; |
6 | 9 | use Doctrine\DBAL\Types\DateTimeType;
|
| 10 | +use Doctrine\DBAL\Types\ConversionException; |
7 | 11 | use Doctrine\DBAL\Platforms\AbstractPlatform;
|
8 | 12 |
|
9 | 13 | class CarbonType extends DateTimeType
|
10 | 14 | {
|
| 15 | + /** |
| 16 | + * @var null|\DateTimeZone |
| 17 | + */ |
| 18 | + private static $utc = null; |
| 19 | + |
| 20 | + /** |
| 21 | + * Function name to call on AbstractPlatform to get the relevent string format. |
| 22 | + * |
| 23 | + * @var string |
| 24 | + */ |
| 25 | + protected $getFormatString = 'getDateTimeFormatString'; |
| 26 | + |
| 27 | + /** |
| 28 | + * Converts the Datetime to UTC before storing to database. |
| 29 | + * |
| 30 | + * @param mixed $value |
| 31 | + * @param AbstractPlatform $platform |
| 32 | + * |
| 33 | + * @return mixed|null |
| 34 | + */ |
| 35 | + public function convertToDatabaseValue($value, AbstractPlatform $platform) |
| 36 | + { |
| 37 | + if ($value === null) { |
| 38 | + return null; |
| 39 | + } |
| 40 | + |
| 41 | + if (is_null(self::$utc)) { |
| 42 | + self::$utc = new \DateTimeZone('UTC'); |
| 43 | + } |
| 44 | + |
| 45 | + if ($value instanceof DateTime) { |
| 46 | + $value->setTimezone(self::$utc); |
| 47 | + } |
| 48 | + |
| 49 | + return parent::convertToDatabaseValue($value, $platform); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Converts the Datetime from UTC to default timezone. |
| 54 | + * |
| 55 | + * @param mixed $value |
| 56 | + * @param AbstractPlatform $platform |
| 57 | + * |
| 58 | + * @return Carbon|null |
| 59 | + * @throws ConversionException |
| 60 | + * @throws InvalidArgumentException |
| 61 | + */ |
11 | 62 | public function convertToPHPValue($value, AbstractPlatform $platform)
|
12 | 63 | {
|
13 |
| - $result = parent::convertToPHPValue($value, $platform); |
| 64 | + if ($value === null || $value instanceof Carbon) { |
| 65 | + return $value; |
| 66 | + } |
| 67 | + |
| 68 | + if (is_null(self::$utc)) { |
| 69 | + self::$utc = new \DateTimeZone('UTC'); |
| 70 | + } |
| 71 | + |
| 72 | + $converted = Carbon::createFromFormat( |
| 73 | + $platform->{$this->getFormatString}(), |
| 74 | + $value, |
| 75 | + self::$utc |
| 76 | + ); |
| 77 | + $converted->setTimezone(new DateTimeZone(date_default_timezone_get())); |
14 | 78 |
|
15 |
| - if ($result instanceof \DateTime) { |
16 |
| - return Carbon::instance($result); |
| 79 | + if (! $converted) { |
| 80 | + throw ConversionException::conversionFailedFormat( |
| 81 | + $value, |
| 82 | + $this->getName(), |
| 83 | + $platform->{$this->getFormatString}() |
| 84 | + ); |
17 | 85 | }
|
18 | 86 |
|
19 |
| - return $result; |
| 87 | + return $converted; |
20 | 88 | }
|
21 | 89 | }
|
0 commit comments