Skip to content

Instantly share code, notes, and snippets.

@romaricdrigon
Last active March 19, 2019 15:13
Show Gist options
  • Select an option

  • Save romaricdrigon/3213bd21d339d6f211361130430b6fd3 to your computer and use it in GitHub Desktop.

Select an option

Save romaricdrigon/3213bd21d339d6f211361130430b6fd3 to your computer and use it in GitHub Desktop.
Type Doctrine custom
<?php
namespace App\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
class DateTimeUtcType extends Type
{
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getDateTimeTypeDeclarationSQL($fieldDeclaration);
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (null === $value) {
return $value;
}
if (!$value instanceof \DateTime) {
throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['null', 'DateTime']);
}
$value->setTimezone(new \DateTimeZone('UTC'));
return $value->format($platform->getDateTimeFormatString());
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null || $value instanceof \DateTime) {
return $value;
}
$val = \DateTime::createFromFormat($platform->getDateTimeFormatString(), $value, new \DateTimeZone('UTC'));
if (!$val) {
throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString());
}
return $val;
}
public function getName()
{
return 'datetime_utc';
}
}
# Dans app/config/config.yml ou config/packages/doctrine.yaml
doctrine:
dbal:
types:
datetime_utc: App\Type\DateTimeUtcType
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment