Last active
March 19, 2019 15:13
-
-
Save romaricdrigon/3213bd21d339d6f211361130430b6fd3 to your computer and use it in GitHub Desktop.
Type Doctrine custom
This file contains hidden or 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 | |
| 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'; | |
| } | |
| } |
This file contains hidden or 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
| # 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