Skip to content

Instantly share code, notes, and snippets.

@graceman9
Created November 23, 2023 05:22
Show Gist options
  • Save graceman9/3c6d7662eb3acea9c46253551c7d6721 to your computer and use it in GitHub Desktop.
Save graceman9/3c6d7662eb3acea9c46253551c7d6721 to your computer and use it in GitHub Desktop.
Doctrine atom date type
<?php
namespace App\Doctrine\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
class AtomDateTimeType extends Type
{
const ATOM_DATETIME = 'atom_datetime';
public function getSQLDeclaration(
array $column,
AbstractPlatform $platform
): string {
/*
* ATOM format is a specific ISO 8601 timestamp representation that
* follows the pattern Y-m-d\TH:i:sP in PHP. Here's an example of a
* date in ATOM format: 2005-08-15T15:52:01+00:00.
*
* To calculate the length, let's break it down:
*
* => 2005-08-15 is the date part, which is always 10 characters.
* => T is a separator, which is 1 character.
* => 15:52:01 is the time part, which is always 8 characters.
* => +00:00 is the timezone offset part, which is always 6 characters.
*
* So in total, an ATOM format date/time is always a
* ## 25 characters long string ##.
*/
return 'VARCHAR(25)';
}
public function convertToPHPValue(
$value,
AbstractPlatform $platform
): ?\DateTime {
if (empty($value) || !is_string($value) || 25 !== strlen($value)) {
return null;
}
$atomDateTime = \DateTime::createFromFormat(\DateTime::ATOM, $value);
if (!$atomDateTime) {
throw ConversionException::conversionFailedFormat(
$value,
$this->getName(),
\DateTime::ATOM
);
}
return $atomDateTime;
}
public function convertToDatabaseValue(
$value,
AbstractPlatform $platform
): ?string {
return ($value instanceof \DateTimeInterface)
? $value->format(\DateTime::ATOM)
: null;
}
public function getName(): string
{
return self::ATOM_DATETIME;
}
}
doctrine:
dbal:
types:
atom_datetime: App\Doctrine\Type\AtomDateTimeType
<?php
#[ORM\Entity(repositoryClass:TaskRepository::class)]
class Task
{
// ...
// The most common way, that matches the rest of Doctrine settings:
#[ORM\Column(type: 'atom_datetime')]
private \DateTime $mostCommonWay;
// Alternative way using the Constant instead of a hardcoded string:
#[ORM\Column(type: AtomDateTimeType::ATOM_DATETIME)]
private \DateTime $alternativeWay;
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment