Skip to content

Instantly share code, notes, and snippets.

@carestad
Last active May 26, 2021 08:15
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 carestad/1e93150956db898a036abeeabf366a1f to your computer and use it in GitHub Desktop.
Save carestad/1e93150956db898a036abeeabf366a1f to your computer and use it in GitHub Desktop.
Doctrine DBAL Timestamp type for use with Laravel
<?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;
}
}
@carestad
Copy link
Author

To implement, add the following to the up()/down() methods of the migrations where it is needed, or in a service provider:

use Doctrine\DBAL\Types\Type;

if (! Type::hasType('timestamp')) {
    Type::addType('timestamp', Timestamp::class);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment