Last active
April 13, 2018 12:37
-
-
Save pwm/6ecb56ffaaeffda7ed1bb73a62805d70 to your computer and use it in GitHub Desktop.
UuidV4 Doctrine DBAL type
This file contains 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 | |
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