Last active
February 22, 2016 12:40
-
-
Save coudenysj/6dc8ba55c43b97143a6c to your computer and use it in GitHub Desktop.
Doctrine DateTimeType supporting MySQL fractional seconds
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 | |
// add this line somewhere in the bootstrap | |
\Doctrine\DBAL\Types\Type::overrideType('datetime', 'My\Project\DBAL\Types\DateTimeType'); |
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 | |
/** | |
* A custom type type for datetime(3) in MySQL. | |
* | |
* @see http://www.doctrine-project.org/jira/browse/DBAL-1084 | |
*/ | |
namespace My\Project\DBAL\Types; | |
use Doctrine\DBAL\Types\ConversionException; | |
use Doctrine\DBAL\Platforms\AbstractPlatform; | |
class DateTimeType extends \Doctrine\DBAL\Types\DateTimeType | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function convertToDatabaseValue($value, AbstractPlatform $platform) | |
{ | |
if ($value === null) { | |
return null; | |
} | |
$format = $platform->getDateTimeFormatString(); | |
if ((int) $value->format('u') === 0) { | |
$format .= '.u'; | |
} | |
return $value->format($format); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function convertToPHPValue($value, AbstractPlatform $platform) | |
{ | |
if ($value === null || $value instanceof \DateTime) { | |
return $value; | |
} | |
$format = $platform->getDateTimeFormatString(); | |
if (preg_match('/.+\.\d+$/', $value)) { | |
$format .= '.u'; | |
} | |
$val = \DateTime::createFromFormat($format, $value); | |
if (!$val) { | |
throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString() . '.u'); | |
} | |
return $val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment