Skip to content

Instantly share code, notes, and snippets.

@paulinevos
Created February 21, 2019 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulinevos/95ef28c2606f650943aef034efb03d05 to your computer and use it in GitHub Desktop.
Save paulinevos/95ef28c2606f650943aef034efb03d05 to your computer and use it in GitHub Desktop.
Doctrine Binary UUID type
<?php
declare(strict_types=1);
namespace Entity\Id;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Ramsey\Uuid\Uuid;
use Entity\Id\Exception\InvalidIdException;
final class BinaryUuid
{
/**
* @var string
*/
protected $id;
public function __construct(string $id = null)
{
parent::__construct($id ?? Uuid::uuid4()->toString());
}
public function getId(): string
{
return $this->id;
}
public function __toString()
{
return $this->id;
}
public function jsonSerialize()
{
return $this->id;
}
public function getBytes(): string
{
return Uuid::fromString($this->id)->getBytes();
}
/**
* @throws InvalidIdException
*/
public function validate($id): void
{
try {
Uuid::fromString($id);
} catch (InvalidUuidStringException $e) {
throw new InvalidIdException($id);
}
}
public function toString(): string
{
return $this->__toString();
}
}
<?php
declare(strict_types=1);
namespace Infrastructure\Persistence\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Ramsey\Uuid\Doctrine\UuidBinaryType;
final class BinaryUuidType extends UuidBinaryType
{
protected function mapsToIdClass(): string
{
return BinaryUuid::class;
}
/**
* @throws \Doctrine\DBAL\Types\ConversionException
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
$uuid = parent::convertToPHPValue($value, $platform);
$className = $this->mapsToIdClass();
return new $className($uuid->toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment