Created
February 21, 2019 10:23
-
-
Save paulinevos/95ef28c2606f650943aef034efb03d05 to your computer and use it in GitHub Desktop.
Doctrine Binary UUID 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); | |
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(); | |
} | |
} |
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); | |
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