Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Created January 8, 2013 16:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathiasverraes/4485025 to your computer and use it in GitHub Desktop.
Save mathiasverraes/4485025 to your computer and use it in GitHub Desktop.
Doctrine2 DBAL type to store Money objects in a single field.
<?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;
}
}
@ricardosaracino
Copy link

ricardosaracino commented Feb 12, 2017

you don't want to store the currency with the amount you won't be able to sum or use conditions with db queries

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