Skip to content

Instantly share code, notes, and snippets.

@enumag
Created May 15, 2017 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enumag/eb933758473bb8fc6af0e204b58ae3e2 to your computer and use it in GitHub Desktop.
Save enumag/eb933758473bb8fc6af0e204b58ae3e2 to your computer and use it in GitHub Desktop.
UtcDateTimeType
<?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