Skip to content

Instantly share code, notes, and snippets.

@fhuitelec
Last active October 12, 2017 13:37
Show Gist options
  • Save fhuitelec/e7a0224a80bf1577badb86291965112e to your computer and use it in GitHub Desktop.
Save fhuitelec/e7a0224a80bf1577badb86291965112e to your computer and use it in GitHub Desktop.
[Doctrine custom type] Wrap primitives and map them in doctrine #symfony #doctrine #custom
doctrine:
dbal:
# [...]
types:
member_id: My\Super\Namespace\Infrastructure\ORM\Type\MyCustomIdType
<?php
namespace My\Super\Namespace\Domain\YourDomainSystem\Identity\CustomId;
use Assert\Assert;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
class CustomId
{
/** @var UuidInterface */
private $id;
/**
* @param string $uuid
*/
public function __construct($uuid)
{
Assert::that($uuid)
->uuid();
$this->id = Uuid::fromString($uuid);
}
/** @return UuidInterface */
public function getId()
{
return $this->id;
}
/** @return string */
function __toString()
{
return $this->id->toString();
}
}
<?php
namespace My\Super\Namespace\Infrastructure\ORM\Type;
use My\Super\Namespace\Domain\YourDomainSystem\Identity\CustomId;
class MyCustomIdType extends Type
{
const NAME = 'custom_id';
/**
* @param array $fieldDeclaration
* @param AbstractPlatform $platform
*
* @return string
*/
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getGuidTypeDeclarationSQL($fieldDeclaration);
}
/**
* @param mixed $value
* @param AbstractPlatform $platform
*
* @return mixed|CustomId
* @throws ConversionException
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if (empty($value)) {
throw ConversionException::conversionFailed($value, self::NAME);
}
if ($value instanceof CustomId) {
return $value;
}
try {
$customId = new CustomId($value);
} catch (\InvalidArgumentException $e) {
throw ConversionException::conversionFailed($value, self::NAME);
}
return $customId;
}
/**
* @param mixed $value
* @param AbstractPlatform $platform
*
* @return null|string
* @throws ConversionException
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (empty($value)) {
return null;
}
if ($value instanceof CustomId) {
return (string) $value;
}
throw ConversionException::conversionFailed($value, self::NAME);
}
/** @return string */
public function getName()
{
return self::NAME;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment