- Notifications
You must be signed in to change notification settings - Fork3
Symfony bundle for moneyphp library
License
yceruto/money-bundle
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Symfony integration of thehttps://github.com/moneyphp/money library. For more information on how the MoneyPHP library works,please refer to its official documentationhttps://www.moneyphp.org.
This bundle is compatible with PHP 8.1 and above, as well as Symfony versions 5.4 and later.
composer require yceruto/money-bundle
If you are not usingsymfony/flex
, make sure to add the bundle to theconfig/bundles.php
file. This will ensure that itis correctly registered and can be used in your application.
Applications often require a specific subset of currencies from different data sources. To facilitate this, you canimplement theMoney\Currencies
interface, which provides a list of available currencies and the subunit for each currency.
The following currencies classes are available as services:
- Money\Currencies\Currencies (alias for AggregateCurrencies)
- Money\Currencies\CurrencyList
- Money\Currencies\ISOCurrencies
- Money\Currencies\BitcoinCurrencies
- Money\Currencies\CryptoCurrencies
TheCurrencies
interface is an alias for theMoney\Currencies\AggregateCurrencies
service, which comes with defaultcurrency providers.
The providers are injected into theAggregateCurrencies
service in the specified order. If you want to add more providers,you need to implement theMoney\Currencies
interface and tag the service withmoney.currencies
.
TheMoney\Currencies\CurrencyList
provider retrieves the currencies from the money configuration:
# config/packages/money.yamlmoney:currencies:FOO:2
The list consists of pairs of currency codes (strings) and subunits (integers). You can also use this configuration tooverride the subunit forMoney\Currencies\ISOCurrencies
.
In many cases, you may not know the exact currency that you will be formatting or parsing. For these scenarios, we haveprovided an aggregate formatter and parser service that allows you to configure multiple formatters/parsers and thenchoose the most appropriate one based on the value. You can find more information about this in the Formatting andParsing section.
Money formatters can be helpful when you need to display a monetary value in a specific format. They allow you to convert amoney object into a human-readable string, making it easier to present financial data to users. By using formatters, youcan ensure that the money values you display are clear and easy to understand.
The following formatter classes are available as services:
- Money\Formatter\MoneyFormatter (alias for AggregateMoneyFormatter)
- Money\Formatter\IntMoneyFormatter (default if Intl extension is enabled)
- Money\Formatter\IntLocalizedMoneyFormatter (available if Intl is enabled)
- Money\Formatter\DecimalMoneyFormatter (default if Intl extension is disabled)
- Money\Formatter\BitcoinMoneyFormatter (available for
XBT
currency code)
You can use theMoney\MoneyFormatter
interface as a dependency for any service because it is an alias for theMoney\Formatter\AggregateMoneyFormatter
service, and it comes with default formatters.
Use the following configuration to set default values for the current formatters:
# config/packages/money.yamlmoney:formatters:intl:number_locale:'en_US'number_style:2# \NumberFormatter::CURRENCYnumber_pattern:nullbitcoin:fraction_digits:8
During a Symfony request, the money formatter will consider the current request locale when formatting the money object.This ensures that the formatted output is localized and suitable for the user's location.
To register a custom formatter, you will need to implement theMoney\MoneyFormatter
interface and tag the service withmoney.formatter
and the currencycode
attribute that the formatter supports. This will allow you to use your customformatter to format monetary values in a specific currency. If your new formatter supports any currency, you can set thecode
attribute to*
. This will allow the formatter to be used for any currency.
Money parsers can help automate the process of extracting monetary value from text, making it more efficient and accurate.
The following parser classes are available as services:
- Money\Parser\MoneyParser (alias for AggregateMoneyParser)
- Money\Parser\IntMoneyParser (default if Intl extension is enabled)
- Money\Parser\IntLocalizedDecimalParser (available if Intl is enabled)
- Money\Parser\DecimalMoneyParser (default if Intl extension is disabled)
- Money\Parser\BitcoinMoneyParser (available for
XBT
currency code)
You can use theMoney\MoneyParser
interface as a dependency for any service because it is an alias for theMoney\Parser\AggregateMoneyParser
service, and it comes with default parsers.
To register a custom parser, you should implement theMoney\MoneyParser
interface and tag the service withmoney.parser
.This will enable you to use your custom parser to parse monetary values from a given text.
To convert aMoney
instance from one currency to another, you need to use theMoney\Converter
service. This class relieson theCurrencies
andExchange
services. TheExchange
service returns aCurrencyPair
, which represents a combinationof the base currency, counter currency, and the conversion ratio.
The following exchange classes are available as services:
- Money\Exchange (alias for FixedExchange)
- Money\Exchange\FixedExchange
- Money\Exchange\IndirectExchange
- Money\Exchange\ReversedCurrenciesExchange
In some cases, you may want theMoney\Converter
service to also resolve the reverse of a givenCurrencyPair
if the originalcannot be found. To add this capability, you can inject theConverter $reversedConverter
argument, which is an alias formoney.reversed_converter
service. If a reverseCurrencyPair
can be found, it is used as a divisor of1
to calculatethe reverse conversion ratio.
To configure theMoney\Exchange\FixedExchange
service, you can use the following configuration:
# config/packages/money.yamlmoney:exchanges:fixed:EUR:USD:'1.10'
Note: Integration with third-party services likeSwap andExchangeris currently outside the scope of this bundle.
By design, theMoney\Money
value object is immutable, which means that it is not possible to change the original amount and currencyvalues after it is created. To address this, this bundle provides a DTO model calledMoneyDto
that can be used in varioussituations, such as user inputs, API requests, form handling, validation, etc. This model allows you to modify the amountand currency values, which can be useful in scenarios where you need to change these values before creating a newMoney\Money
instance.
$dto =newMoneyDto();// default null for amount and currency properties$dto = MoneyDto::fromMoney(Money::EUR(100));// returns a new DTO instance$dto = MoneyDto::fromAmount(100);// default EUR currency$dto = MoneyDto::fromCurrency('USD');// default 0 amount$money =$dto->toMoney();// returns a new Money\Money instance
The SymfonyMoneyType
will be updated to derive thescale
anddivisor
options from thecurrency
value:
$formBuilder->add('price', MoneyType::class, ['currency' =>'CUP'])
Contrary to typical usage, it is not supposed to work directly with theMoney\Money
object. Instead, it expects anumeric property to be associated with this form field.
You can disable this integration by modifying the configuration:
# config/packages/money.yamlmoney:form:enabled:false
If you have installedtwig/twig
as your template engine, you can use the Twig filter provided to format your money objectsdirectly in any template page:
{{money|money_format }}
It will follow the same behavior as theMoney\Formatter\MoneyFormatter
service.
You can disable this integration by modifying the configuration:
# config/packages/money.yamlmoney:twig:enabled:false
Doctrine allows you to map an embedded object to a database column using theEmbedded
attribute and this bundle providestheMoney\Money
ORM mapping definitions for use with the Doctrine bundle, if it is enabled. This means that you can useDoctrine's entity manager to persist and retrieve your entities with the embedded money values, without having to manuallyconfigure the ORM mappings. This can simplify your development process and allow you to focus on other aspects of your application:
useDoctrine\ORM\Mapping\Embedded;useMoney\Money;class Product{ #[Embedded]privateMoney$price;}
Important: To ensure proper processing of theMoney\Money
mapping, it is important to register this bundle inbundles.php
before registering theDoctrineBundle
.
// config/bundles.phpreturn [// ...Yceruto\MoneyBundle\MoneyBundle::class => ['all' =>true],Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' =>true],// ...];
You can also use the fields of embedded classes that have been mapped using Doctrine in DQL (Doctrine Query Language)queries. These can be used just as if they were declared in the Product class itself:
SELECT pFROM Product pWHEREp.price.amount>1000ANDp.price.currency.code='EUR'
You can disable this integration by modifying the configuration:
# config/packages/money.yamlmoney:doctrine:enabled:false
This software is published under theMIT License
About
Symfony bundle for moneyphp library