Skip to content

Instantly share code, notes, and snippets.

@pwm
Last active April 13, 2018 12:37
Show Gist options
  • Save pwm/6ecb56ffaaeffda7ed1bb73a62805d70 to your computer and use it in GitHub Desktop.
Save pwm/6ecb56ffaaeffda7ed1bb73a62805d70 to your computer and use it in GitHub Desktop.
UuidV4 Doctrine DBAL type
<?php
declare(strict_types=1);
use Pwm\UuidV4\UuidV4;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
final class UuidV4Type extends Type
{
public const NAME = 'uuid_v4';
public const LENGTH = 36;
public function getName(): string
{
return self::NAME;
}
public function convertToPHPValue($value, AbstractPlatform $platform): UuidV4
{
$uuid = $value instanceof UuidV4
? $value
: new UuidV4($value);
if ($uuid instanceof UuidV4) {
return $uuid;
}
throw ConversionException::conversionFailed($value, self::NAME);
}
public function convertToDatabaseValue($value, AbstractPlatform $platform): string
{
if ($value instanceof UuidV4) {
return $value->toValue();
}
throw ConversionException::conversionFailedInvalidType($value, self::NAME, [UuidV4::class]);
}
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string
{
return $platform->getVarcharTypeDeclarationSQL(['length' => self::LENGTH, 'fixed' => true]);
}
public function getDefaultLength(AbstractPlatform $platform): int
{
return self::LENGTH;
}
public function requiresSQLCommentHint(AbstractPlatform $platform): bool
{
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment