add implementation
All checks were successful
/ ls (push) Successful in 19s

This commit is contained in:
lubiana 2024-06-01 22:28:11 +02:00
parent 77fba06a1f
commit 13bfbbe528
Signed by: lubiana
SSH key fingerprint: SHA256:gkqM8DUX4Blf6P52fycW8ISTd+4eAHH+Uzu9iyc8hAM
20 changed files with 5598 additions and 0 deletions

74
src/Types/UlidType.php Normal file
View 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]);
}
}