Created
February 22, 2013 13:48
-
-
Save Sitebase/5013494 to your computer and use it in GitHub Desktop.
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.
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
\Doctrine\DBAL\Types\Type::addType('uuid', 'BuboBox\Doctrine2\DBAL\Types\UuidType'); |
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 | |
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.