Last active
May 26, 2021 08:15
-
-
Save carestad/1e93150956db898a036abeeabf366a1f to your computer and use it in GitHub Desktop.
Doctrine DBAL Timestamp type for use with Laravel
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 Database\Migrations\Types; | |
use DateTime; | |
use Doctrine\DBAL\Platforms\AbstractPlatform; | |
use Doctrine\DBAL\Types\ConversionException; | |
use Doctrine\DBAL\Types\PhpDateTimeMappingType; | |
use Doctrine\DBAL\Types\Type; | |
/** | |
* Timestamp type for the Doctrine 3 ORM | |
*/ | |
class Timestamp extends Type implements PhpDateTimeMappingType | |
{ | |
/** | |
* Type name | |
* | |
* @var string | |
*/ | |
const TIMESTAMP = 'timestamp'; | |
/** | |
* @inheritDoc | |
*/ | |
public function getName() | |
{ | |
return self::TIMESTAMP; | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) | |
{ | |
$declaration = strtoupper(self::TIMESTAMP); | |
if (isset($fieldDeclaration['notnull']) && $fieldDeclaration['notnull'] == true) { | |
return $declaration; | |
} | |
return $declaration . ' NULL'; | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function convertToDatabaseValue($value, AbstractPlatform $platform) | |
{ | |
if (null === $value) { | |
return null; | |
} | |
if ($value instanceof DateTime) { | |
return $value->getTimestamp(); | |
} | |
throw ConversionException::conversionFailedInvalidType( | |
$value, | |
$this->getName(), | |
['null', 'DateTime'] | |
); | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function convertToPHPValue($value, AbstractPlatform $platform) | |
{ | |
if (null === $value) { | |
return null; | |
} | |
$st = new DateTime(); | |
$st->setTimestamp($value); | |
return $st; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To implement, add the following to the
up()
/down()
methods of the migrations where it is needed, or in a service provider: