### Install Brick/Money PHP Library with Composer Source: https://github.com/brick/money/blob/master/README.md This command installs the Brick/Money library using Composer, the PHP dependency manager. It fetches the latest stable version of the library and adds it to your project's dependencies, enabling precise monetary calculations. ```bash composer require brick/money ``` -------------------------------- ### Combine Multiple Money Instances in Brick\Money Source: https://github.com/brick/money/blob/master/README.md This example illustrates how to chain multiple arithmetic operations, such as adding and subtracting, with different Money instances. It shows how to calculate a final amount by combining costs, shipping, and discounts. ```php use Brick\Money\Money; $cost = Money::of(25, 'USD'); $shipping = Money::of('4.99', 'USD'); $discount = Money::of('2.50', 'USD'); echo $cost->plus($shipping)->minus($discount); // USD 27.49 ``` -------------------------------- ### PHP: Customizing Money Formatting with NumberFormatter Source: https://github.com/brick/money/blob/master/README.md This example shows how to achieve highly customized money formatting by providing a pre-configured `NumberFormatter` instance. It allows setting custom currency symbols, grouping separators, and minimum fraction digits. ```php $formatter = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY); $formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, 'US$'); $formatter->setSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, '·'); $formatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 2); $money = Money::of(5000, 'USD'); echo $money->formatWith($formatter); // US$5·000.00 ``` -------------------------------- ### PHP: Using a Custom Currency with Money Object Source: https://github.com/brick/money/blob/master/README.md Once a custom `Currency` instance is defined, this example shows how to use it directly when creating a `Money` object, allowing for financial operations with non-ISO 4217 currencies. ```php $money = Money::of('0.123', $bitcoin); // XBT 0.12300000 ``` -------------------------------- ### PHP: Using BaseCurrencyProvider for Relative Exchange Rates Source: https://github.com/brick/money/blob/master/README.md This example shows how `BaseCurrencyProvider` can be used to derive exchange rates between any two currencies when all rates are relative to a single base currency (e.g., EUR). It builds upon an existing exchange rate provider to perform indirect conversions. ```php use Brick\Money\ExchangeRateProvider\ConfigurableProvider; use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider; $provider = new ConfigurableProvider(); $provider->setExchangeRate('EUR', 'USD', '1.1'); $provider->setExchangeRate('EUR', 'GBP', '0.9'); $provider = new BaseCurrencyProvider($provider, 'EUR'); $provider->getExchangeRate('EUR', 'USD'); // 1.1 $provider->getExchangeRate('USD', 'EUR'); // 10/11 $provider->getExchangeRate('GBP', 'USD'); // 11/9 ``` -------------------------------- ### Apply Rounding Modes to Brick\Money Operations Source: https://github.com/brick/money/blob/master/README.md This example shows how to handle rounding when arithmetic operations result in values that exceed the currency's default scale. It demonstrates using RoundingMode to explicitly define how results should be rounded, preventing RoundingNecessaryException. ```php use Brick\Money\Money; use Brick\Math\RoundingMode; $money = Money::of(50, 'USD'); $money->plus('0.999'); // RoundingNecessaryException $money->plus('0.999', RoundingMode::DOWN); // USD 50.99 $money->minus('0.999'); // RoundingNecessaryException $money->minus('0.999', RoundingMode::UP); // USD 49.01 $money->multipliedBy('1.2345'); // RoundingNecessaryException $money->multipliedBy('1.2345', RoundingMode::DOWN); // USD 61.72 $money->dividedBy(3); // RoundingNecessaryException $money->dividedBy(3, RoundingMode::UP); // USD 16.67 ``` -------------------------------- ### ORM Integration with Money Object (PHP) Source: https://github.com/brick/money/blob/master/README.md This example illustrates how to integrate the Money object with an ORM like Doctrine. It demonstrates storing the amount and currency separately in entity properties and converting them to and from a Money object within the getter and setter methods, ensuring proper encapsulation and type safety. ```php class Entity { private int $price; private string $currencyCode; public function getPrice() : Money { return Money::ofMinor($this->price, $this->currencyCode); } public function setPrice(Money $price) : void { $this->price = $price->getMinorAmount()->toInt(); $this->currencyCode = $price->getCurrency()->getCurrencyCode(); } } ``` -------------------------------- ### Create Money Object from Minor Units (Cents) in PHP Source: https://github.com/brick/money/blob/master/README.md This PHP example shows how to instantiate a Money object using Money::ofMinor(). This method is useful when the monetary value is provided as an integer representing the smallest currency unit (e.g., cents for USD), ensuring exact calculations without floating-point inaccuracies. ```php use Brick\Money\Money; $money = Money::ofMinor(1234, 'USD'); // USD 12.34 ``` -------------------------------- ### Define Custom Scale with CustomContext in Brick\Money Source: https://github.com/brick/money/blob/master/README.md This example illustrates how to use CustomContext to override the default currency scale. It allows specifying a custom number of decimal places for monetary values, providing flexibility for specific calculation requirements beyond standard ISO 4217 definitions. ```php use Brick\Money\Money; use Brick\Money\Context\CustomContext; use Brick\Math\RoundingMode; $money = Money::of(10, 'USD', new CustomContext(scale: 4)); // USD 10.0000 $money->dividedBy(7, RoundingMode::UP); // USD 1.4286 ``` -------------------------------- ### PHP: Configuring PDOProvider for Exchange Rates Source: https://github.com/brick/money/blob/master/README.md This snippet demonstrates how to initialize `PDOProvider` to fetch exchange rates from a database table. It requires a PDO instance and a `PDOProviderConfiguration` object specifying table and column names for currency codes and exchange rates. ```php use Brick\Money\ExchangeRateProvider\PDOProvider; use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration; $pdo = new \PDO(...); $configuration = new PDOProviderConfiguration( tableName: 'exchange_rates', exchangeRateColumnName: 'exchange_rate', sourceCurrencyColumnName: 'source_currency_code', targetCurrencyColumnName: 'target_currency_code', ); $provider = new PDOProvider($pdo, $configuration); ``` -------------------------------- ### Configure Manual Exchange Rates with ConfigurableProvider Source: https://github.com/brick/money/blob/master/README.md Illustrates how to set up and use `ConfigurableProvider` to manually define exchange rates between different currencies. This provider allows for explicit control over the conversion rates used by the `CurrencyConverter`. ```php use Brick\Money\ExchangeRateProvider\ConfigurableProvider; $provider = new ConfigurableProvider(); $provider->setExchangeRate('EUR', 'USD', '1.0987'); $provider->setExchangeRate('USD', 'EUR', '0.9123'); ``` -------------------------------- ### PHP: Defining a Custom Currency Instance Source: https://github.com/brick/money/blob/master/README.md This snippet illustrates how to create a custom `Currency` object, such as Bitcoin. It requires a currency code, an optional numeric code, a name, and a default scale for precision. ```php use Brick\Money\Currency; use Brick\Money\Money; $bitcoin = new Currency( 'XBT', // currency code 0, // numeric currency code, useful when storing monies in a database; set to 0 if unused 'Bitcoin', // currency name 8 // default scale ); ``` -------------------------------- ### Convert RationalMoney to Money with Custom Context Source: https://github.com/brick/money/blob/master/README.md Illustrates converting a `RationalMoney` back to a `Money` object while applying a custom context and a specific rounding mode. This allows for fine-grained control over the precision and rounding of the final monetary value. ```php ... ->to(new CustomContext(scale: 8), RoundingMode::UP); // EUR 25.07015334 ``` -------------------------------- ### Allocate Money with Cash Rounding Context Source: https://github.com/brick/money/blob/master/README.md Shows how `Money` allocation interacts with a `CashContext`. When a `CashContext` is applied, the allocation results are rounded according to the specified cash step, ensuring compliance with physical currency denominations. ```php use Brick\Money\Money; use Brick\Money\Context\CashContext; $profit = Money::of('987.65', 'CHF', new CashContext(step: 5)); [$a, $b, $c] = $profit->allocate(48, 41, 11); // CHF 474.10, CHF 404.95, CHF 108.60 ``` -------------------------------- ### Create and Populate a MoneyBag with Mixed Currencies Source: https://github.com/brick/money/blob/master/README.md Demonstrates the usage of `MoneyBag` to aggregate monetary amounts in different currencies. `MoneyBag` is a mutable class that allows adding `Money`, `RationalMoney`, or even other `MoneyBag` instances. ```php use Brick\Money\Money; use Brick\Money\MoneyBag; $eur = Money::of('12.34', 'EUR'); $jpy = Money::of(123, 'JPY'); $moneyBag = new MoneyBag(); $moneyBag->add($eur); $moneyBag->add($jpy); ``` -------------------------------- ### Allocate Money According to Ratios Source: https://github.com/brick/money/blob/master/README.md Explains how to allocate a `Money` amount among multiple recipients based on a list of integer ratios. The `allocate()` method distributes the profit proportionally, with any remainder spread across the first allocated amounts. ```php use Brick\Money\Money; $profit = Money::of('987.65', 'CHF'); [$a, $b, $c] = $profit->allocate(48, 41, 11); // CHF 474.08, CHF 404.93, CHF 108.64 ``` -------------------------------- ### Split Money into Equal Parts with Remainder Distribution Source: https://github.com/brick/money/blob/master/README.md Demonstrates how to split a `Money` object into a specified number of parts. The `split()` method automatically distributes any remainder to the first monies in the resulting list, ensuring the total sum matches the original amount. ```php use Brick\Money\Money; $money = Money::of(100, 'USD'); [$a, $b, $c] = $money->split(3); // USD 33.34, USD 33.33, USD 33.33 ``` -------------------------------- ### Convert Money Between Currencies Using CurrencyConverter Source: https://github.com/brick/money/blob/master/README.md Explains how to use the `CurrencyConverter` to convert any type of money object (`Money`, `RationalMoney`, `MoneyBag`) into a `Money` object of a different currency. It requires an `ExchangeRateProvider` and performs precise calculations internally. ```php use Brick\Money\CurrencyConverter; $exchangeRateProvider = ...; $converter = new CurrencyConverter($exchangeRateProvider); // optionally provide a Context here $money = Money::of('50', 'USD'); $converter->convert($money, 'EUR', roundingMode: RoundingMode::DOWN); ``` -------------------------------- ### Simplify RationalMoney Fraction to Manage Large Numbers Source: https://github.com/brick/money/blob/master/README.md Shows how to simplify the internal rational number representation of a `RationalMoney` object. This helps in managing potentially very large numerators and denominators that can arise during complex calculations, without altering the actual monetary value. ```php ... ->multipliedBy('1.196') // EUR 7521046000/300000000 ->simplified(); // EUR 3760523/150000 ``` -------------------------------- ### Chain Operations with RationalMoney for Precise Calculations Source: https://github.com/brick/money/blob/master/README.md Demonstrates how to use `RationalMoney` to chain multiple monetary operations (division, addition, multiplication) without intermediate rounding. The amount is internally stored as a rational number (fraction), and rounding is only applied at the final conversion back to a `Money` object. ```php use Brick\Money\Money; use Brick\Math\RoundingMode; $money = Money::of('9.5', 'EUR') // EUR 9.50 ->toRational() // EUR 950/100 ->dividedBy(3) // EUR 950/300 ->plus('17.795') // EUR 6288500/300000 ->multipliedBy('1.196') // EUR 7521046000/300000000 ->to($money->getContext(), RoundingMode::DOWN); // EUR 25.07 ``` -------------------------------- ### Handle Currency Mismatch Exceptions in Brick\Money Source: https://github.com/brick/money/blob/master/README.md This snippet demonstrates that an exception is thrown when attempting to perform arithmetic operations on Money instances with different currencies. The MoneyMismatchException ensures currency consistency and prevents erroneous calculations. ```php use Brick\Money\Money; $a = Money::of(1, 'USD'); $b = Money::of(1, 'EUR'); $a->plus($b); // MoneyMismatchException ``` -------------------------------- ### Perform Basic Arithmetic Operations with Brick\Money Source: https://github.com/brick/money/blob/master/README.md This snippet demonstrates fundamental arithmetic operations on a Money instance, including addition, subtraction, multiplication, and division. Since Money is an immutable class, each operation returns a new Money object with the updated value. ```php use Brick\Money\Money; $money = Money::of(50, 'USD'); echo $money->plus('4.99'); // USD 54.99 echo $money->minus(1); // USD 49.00 echo $money->multipliedBy('1.999'); // USD 99.95 echo $money->dividedBy(4); // USD 12.50 ``` -------------------------------- ### PHP: Formatting Money Objects by Locale Source: https://github.com/brick/money/blob/master/README.md This snippet demonstrates formatting a `Money` object according to a specified locale, such as 'en_US' or 'fr_FR'. This functionality requires the PHP `intl` extension to be enabled. ```php $money = Money::of(5000, 'USD'); echo $money->formatTo('en_US'); // $5,000.00 echo $money->formatTo('fr_FR'); // 5 000,00 $US ``` -------------------------------- ### PHP: Storing and Retrieving Money as Integer Minor Units Source: https://github.com/brick/money/blob/master/README.md This method demonstrates storing money amounts as integers representing minor units (e.g., cents) and subsequently retrieving them. It's suitable when dealing with currencies that consistently use a default scale and helps avoid floating-point inaccuracies. ```php $integerAmount = $money->getMinorAmount()->toInt(); ``` ```php Money::ofMinor($integerAmount, $currencyCode); ``` -------------------------------- ### PHP: Storing and Retrieving Money as Decimal String Source: https://github.com/brick/money/blob/master/README.md This approach involves storing the money amount as a decimal string and then reconstructing the `Money` object. It is advised for most cases where the exact precision of the amount needs to be preserved without loss from floating-point conversion. ```php $decimalAmount = (string) $money->getAmount(); ``` ```php Money::of($decimalAmount, $currencyCode); ``` -------------------------------- ### Use CashContext for Cash Rounding in Brick\Money Source: https://github.com/brick/money/blob/master/README.md This snippet demonstrates the CashContext for handling currencies with specific cash increment rules, such as CHF. It allows defining a 'step' for rounding to the nearest cash denomination, which is particularly useful for physical cash transactions. ```php use Brick\Money\Money; use Brick\Money\Context\CashContext; use Brick\Math\RoundingMode; $money = Money::of(10, 'CHF', new CashContext(step: 5)); // CHF 10.00 $money->dividedBy(3, RoundingMode::DOWN); // CHF 3.30 $money->dividedBy(3, RoundingMode::UP); // CHF 3.35 ``` -------------------------------- ### Create Money Object from Decimal Value in PHP Source: https://github.com/brick/money/blob/master/README.md This PHP code demonstrates how to create a Money object using the Money::of() factory method. It accepts a numeric value (string or float) and a currency code. If the amount requires rounding to fit the currency's decimal places, a RoundingMode can be specified to prevent exceptions. ```php use Brick\Money\Money; $money = Money::of(50, 'USD'); // USD 50.00 $money = Money::of('19.9', 'USD'); // USD 19.90 // Handling rounding for values with too many decimal places $money = Money::of('123.456', 'USD'); // RoundingNecessaryException $money = Money::of('123.456', 'USD', roundingMode: RoundingMode::UP); // USD 123.46 ``` -------------------------------- ### Adjust Scale Automatically with AutoContext in Brick\Money Source: https://github.com/brick/money/blob/master/README.md This snippet demonstrates AutoContext, which automatically adjusts the scale of monetary values to fit the operation result. This context is useful for intermediate calculations where the precision needs to adapt dynamically, though it has limitations with infinite repeating decimals. ```php use Brick\Money\Money; use Brick\Money\Context\AutoContext; $money = Money::of('1.10', 'USD', new AutoContext()); // USD 1.1 $money->multipliedBy('2.5'); // USD 2.75 $money->dividedBy(8); // USD 0.1375 ``` -------------------------------- ### Retrieve Currency Code as String (PHP) Source: https://github.com/brick/money/blob/master/README.md This snippet demonstrates how to extract the 3-letter ISO or custom currency code from a Money object. This code can then be stored in a database field like CHAR(3), VARCHAR, or ENUM for later retrieval. ```php $currencyCode = $money->getCurrency()->getCurrencyCode(); ``` -------------------------------- ### Retrieve Numeric Currency Code (PHP) Source: https://github.com/brick/money/blob/master/README.md This snippet shows how to obtain the numeric currency code from a Money object. This numeric code can be stored as an integer in a database, particularly useful for ISO currencies with numeric representations. ```php $numericCode = $money->getCurrency()->getNumericCode(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.