Created
May 15, 2017 07:56
-
-
Save enumag/eb933758473bb8fc6af0e204b58ae3e2 to your computer and use it in GitHub Desktop.
UtcDateTimeType
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* @copyright Copyright (c) 2016 Ubiquiti Networks, Inc. | |
* @see https://www.ubnt.com/ | |
*/ | |
namespace AppBundle\Database; | |
use Doctrine\DBAL\Platforms\AbstractPlatform; | |
use Doctrine\DBAL\Types\ConversionException; | |
use Doctrine\DBAL\Types\DateTimeType; | |
class UtcDateTimeType extends DateTimeType | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getName() | |
{ | |
return 'datetime_utc'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function requiresSQLCommentHint(AbstractPlatform $platform) | |
{ | |
return true; | |
} | |
/** | |
* @param \DateTime|string|null $value | |
* @param AbstractPlatform $platform | |
* | |
* @return mixed|null | |
*/ | |
public function convertToDatabaseValue($value, AbstractPlatform $platform) | |
{ | |
if (is_string($value)) { | |
$value = new \DateTime($value); | |
} | |
if ($value instanceof \DateTime) { | |
$value = (clone $value)->setTimezone(new \DateTimeZone('UTC')); | |
} | |
return parent::convertToDatabaseValue($value, $platform); | |
} | |
/** | |
* @param mixed $value | |
* @param AbstractPlatform $platform | |
* | |
* @return \DateTime|null | |
* | |
* @throws ConversionException | |
*/ | |
public function convertToPHPValue($value, AbstractPlatform $platform) | |
{ | |
if (null === $value || $value instanceof \DateTime) { | |
return $value; | |
} | |
$converted = \DateTime::createFromFormat( | |
$platform->getDateTimeFormatString(), | |
$value, | |
new \DateTimeZone('UTC') | |
); | |
if ($converted) { | |
$converted->setTimezone(new \DateTimeZone(date_default_timezone_get())); | |
} else { | |
throw ConversionException::conversionFailedFormat( | |
$value, | |
$this->getName(), | |
$platform->getDateTimeFormatString() | |
); | |
} | |
return $converted; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment