Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom doctrine type to store uuid's as binary(16) values in a MySQL database. Set the column type that you want to use as BINARY(16) in MySQL and your good to go.
\Doctrine\DBAL\Types\Type::addType('uuid', 'BuboBox\Doctrine2\DBAL\Types\UuidType');
<?php
namespace BuboBox\Doctrine2\DBAL\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Type that maps a PHP array to a clob SQL type.
*
* @since 2.0
*/
class UuidType extends Type
{
const BINARY = 'binary';
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return sprintf('BINARY(%d)', $fieldDeclaration['length']);
}
public function getName()
{
return self::BINARY;
}
public function convertToPhpValue($value, AbstractPlatform $platform)
{
if ($value !== null) {
$value= unpack('H*', $value);
$hash = array_shift($value);
$uuid = substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
return $uuid;
}
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value !== null) {
return pack('H*', str_replace('-', '',$value));
}
}
}
@knifesk

This comment has been minimized.

knifesk commented Jun 25, 2015

Man, you just saved me hours of headache :)

@ricbra

This comment has been minimized.

ricbra commented Jun 26, 2015

Thanks for sharing this! Perhaps you want to checkout my fork as I've slightly updated the code a bit. For the reasoning behind this you might wanna checkout the post I wrote about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment