This commit is contained in:
parent
77fba06a1f
commit
13bfbbe528
20 changed files with 5598 additions and 0 deletions
74
src/Types/UlidType.php
Normal file
74
src/Types/UlidType.php
Normal file
|
@ -0,0 +1,74 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Lubiana\DoctrineUlid\Types;
|
||||
|
||||
use Doctrine\DBAL\Platforms\AbstractPlatform;
|
||||
use Doctrine\DBAL\Types\Exception\InvalidType;
|
||||
use Doctrine\DBAL\Types\Exception\ValueNotConvertible;
|
||||
use Doctrine\DBAL\Types\Type;
|
||||
use Symfony\Component\Uid\Ulid;
|
||||
|
||||
final class UlidType extends Type
|
||||
{
|
||||
public const NAME = 'ulid';
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
|
||||
{
|
||||
if ($this->hasNativeGuidType($platform)) {
|
||||
return $platform->getGuidTypeDeclarationSQL($column);
|
||||
}
|
||||
|
||||
return $platform->getBinaryTypeDeclarationSQL([
|
||||
'length' => 16,
|
||||
'fixed' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
public function convertToPHPValue(mixed $value, AbstractPlatform $platform): ?Ulid
|
||||
{
|
||||
if ($value instanceof Ulid || $value === null) {
|
||||
return $value;
|
||||
}
|
||||
if (!is_string($value)) {
|
||||
throw InvalidType::new($value, self::NAME, ['null', 'string', self::class]);
|
||||
}
|
||||
try {
|
||||
return Ulid::fromString($value);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw ValueNotConvertible::new($value, self::NAME, null, $e);
|
||||
}
|
||||
}
|
||||
|
||||
public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): ?string
|
||||
{
|
||||
$toStringFunc = fn (Ulid $v) => $v->toRfc4122();
|
||||
if (!$this->hasNativeGuidType($platform)) {
|
||||
$toStringFunc = fn (Ulid $v) => $v->toBinary();
|
||||
}
|
||||
|
||||
if ($value instanceof Ulid) {
|
||||
return $toStringFunc($value);
|
||||
}
|
||||
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!\is_string($value)) {
|
||||
throw InvalidType::new($value, self::NAME, ['null', 'string', self::class]);
|
||||
}
|
||||
try {
|
||||
return $toStringFunc(Ulid::fromString($value));
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw ValueNotConvertible::new($value, self::NAME, null, $e);
|
||||
}
|
||||
}
|
||||
|
||||
private function hasNativeGuidType(AbstractPlatform $platform): bool
|
||||
{
|
||||
return $platform->getGuidTypeDeclarationSQL([]) !== $platform->getStringTypeDeclarationSQL(['fixed' => true, 'length' => 36]);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue