Created
January 8, 2013 16:11
-
-
Save mathiasverraes/4485025 to your computer and use it in GitHub Desktop.
Doctrine2 DBAL type to store Money objects in a single field.
This file contains hidden or 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 Money\Doctrine2; | |
use Money\Money; | |
use Money\Currency; | |
use Doctrine\DBAL\Types\ConversionException; | |
use Doctrine\DBAL\Types\Type; | |
use Doctrine\DBAL\Platforms\AbstractPlatform; | |
/** | |
* Stores Money in a single field, in the smallest unit (cents). eg "EUR 100" | |
* Note that this is only usefull if you don't intend to query on this. | |
* | |
* @example | |
*/ | |
class MoneyType extends Type | |
{ | |
const NAME = 'money'; | |
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform) | |
{ | |
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); | |
} | |
public function convertToPHPValue($value, AbstractPlatform $platform) | |
{ | |
if (is_null($value)) { | |
return null; | |
} | |
list($currency, $amount) = explode(' ', $value, 2); | |
return new Money((int) $amount, new Currency($currency)); | |
} | |
public function convertToDatabaseValue($value, AbstractPlatform $platform) | |
{ | |
if (empty($value)) { | |
return null; | |
} | |
if ($value instanceof Money) { | |
return (string) $value->getCurrency() . ' '. $value->getAmount(); | |
} | |
throw ConversionException::conversionFailed($value, self::NAME); | |
} | |
public function getName() | |
{ | |
return self::NAME; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you don't want to store the currency with the amount you won't be able to sum or use conditions with db queries