A simple PHP library for complex monetary prices management
A simple PHP library for complex monetary prices management
Version 3.x
This new major version aims to avoid rounding errors when working with division and multiplication.
We have replaced almost all
Brick\Money\Moneytypehints toBrick\Money\AbstractMoneyin order to allow usage ofBrick\Money\RationalMoneyinstances as the base for the price object, in order to allow rounding-free division and multiplication. See the new chapter on rounding errors in this documentation for more information.
We have also added type definitions everywhere we could. This introduces some breaking changes.
Using the underlying brick/money library, this simple Price object allows to work with complex composite monetary values which include exclusive, inclusive, VAT (and other potential taxes) and discount amounts. It makes it safer and easier to compute final displayable prices without having to worry about their construction.
composer require whitecube/php-pricesEach Price object has a base Brick\Money\Money or Brick\Money\RationalMoney instance which is considered to be the item's unchanged, per-unit & exclusive amount. All the composition operations, such as adding VAT or applying discounts, are added on top of this base value.
use Whitecube\Price\Price;
$steak = Price::EUR(1850) // Steak costs €18.50/kg
->setUnits(1.476) // Customer had 1.476kg, excl. total is €27.31
->setVat(6) // There is 6% VAT, incl. total is €28.95
->addTax(50) // There also is a €0.50/kg tax (before VAT), incl. total is €29.73
->addDiscount(-100); // We granted a €1.00/kg discount (before VAT), incl. total is €28.16It is common practice and always best to work with amounts represented in the smallest currency unit (minor values) such as "cents".
There are several convenient ways to obtain a Price instance:
| Method | Using major values | Using minor values | Defining units |
|---|---|---|---|
| Constructor | new Price(AbstractMoney $base) |
new Price(AbstractMoney $base) |
new Price(AbstractMoney $base, $units) |
| Brick/Money API | Price::of($major, $currency) |
Price::ofMinor($minor, $currency) |
- |
| Currency API | - | Price::EUR($minor) |
Price::USD($minor, $units) |
| Parsed strings | Price::parse($value, $currency) |
- | Price::parse($value, $currency, $units) |
You can set this basic value by instantiating the Price directly with the desired Brick\Money\Money instance:
use Brick\Money\Money;
use Whitecube\Price\Price;
$base = new Money::ofMinor(500, 'USD'); // $5.00
$single = new Price($base); // 1 x $5.00
$multiple = new Price($base, 4); // 4 x $5.00For convenience, it is also possible to use the shorthand Money factory methods:
use Whitecube\Price\Price;
$major = Price::of(5, 'EUR'); // 1 x €5.00
$minor = Price::ofMinor(500, 'USD'); // 1 x $5.00Using these static calls, you cannot define quantities or units directly with the constructor methods.
For more information on all the available Brick/Money constructors, please take a look at their documentation.
You can also create an instance directly with the intended currency and quantities using the 3-letter currency ISO codes:
use Whitecube\Price\Price;
$single = Price::EUR(500); // 1 x €5.00
$multiple = Price::USD(500, 4); // 4 x $5.00Using these static calls, all monetary values are considered minor values (e.g. cents).
For a list of all available ISO 4217 currencies, take a look at Brick/Money's iso-currencies definition.
Additionnaly, prices can also be parsed from "raw currency value" strings. This method can be useful but should always be used carefully since it may produce unexpected results in some edge-case situations, especially when "guessing" the currency :
use Whitecube\Price\Price;
$guessCurrency = Price::parse('5,5$'); // 1 x $5.50
$betterGuess = Price::parse('JMD 5.50'); // 1 x $5.50
$forceCurrency = Price::parse('10', 'EUR'); // 1 x €10.00
$multiple = Price::parse('6.008 EUR', null, 4); // 4 x €6.01
$force = Price::parse('-5 EUR', 'USD', 4); // 4 x $-5.00Parsing formatted strings is a tricky subject. More information on parsing string values below.
Once set, the base amount can be accessed using the base() method.
Note If you give an instance of
Brick\Money\Moneyas a parameter when instanciating the price object, you will get aBrick\Money\Moneyinstance back. Similarly, instanciating withBrick\Money\RationalMoneywill give you aRationalMoneyobject back.
$perUnit = $price->base(); // Brick\Money\Money
$allUnits = $price->base(false); // Brick\Money\MoneyGetting the currency instance is just as easy:
$currency = $price->currency(); // Brick\Money\CurrencyThe total exclusive amount (with all modifiers except VAT):
$perUnit = $price->exclusive(true); // Brick\Money\Money
$allUnits = $price->exclusive(); // Brick\Money\MoneyThe total inclusive amount (with all modifiers and VAT applied):
$perUnit = $price->inclusive(true); // Brick\Money\Money
$allUnits = $price->inclusive(); // Brick\Money\MoneyThe VAT variables:
$vat = $price->vat(); // Whitecube\Price\Vat
$percentage = $price->vat()->percentage(); // float
$perUnit = $price->vat()->money(true); // Brick\Money\Money
$allUnits = $price->vat()->money(); // Brick\Money\MoneyIt is possible to check whether a price object's total inclusive amount is greater, lesser or equal to another value using the compareTo method:
$price = Price::USD(500, 2); // 2 x $5.00
$price->compareTo(999); // 1
$price->compareTo(1000); // 0
$price->compareTo(1001); // -1
$price->compareTo(Money::of(10, 'USD')); // 0
$price->compareTo(Price::USD(250, 4)); // 0For convenience there also is an equals() method:
$price->equals(999); // false
$price->equals(1000); // true
$price->equals(Money::of(10, 'USD')); // true
$price->equals(Price::USD(250, 4)); // trueIf you don't want to compare final modified values, there is a compareBaseTo method:
$price = Price::USD(500, 2); // 2 x $5.00
$price->compareBaseTo(499); // 1
$price->compareBaseTo(500); // 0
$price->compareBaseTo(501); // -1
$price->compareBaseTo(Money::of(5, 'USD')); // 0
$price->compareBaseTo(Price::USD(500, 4)); // 0The price object will forward all the Brick\Money\Money API method calls to its base value.
Warning: In opposition to Money objects, Price objects are not immutable. Therefore, operations like plus, minus, etc. will directly modify the price's base value instead of returning a new instance.
use Whitecube\Price\Price;
$price = Price::ofMinor(500, 'USD')->setUnits(2); // 2 x $5.00
$price->minus('2.00') // 2 x $3.00
->plus('1.50') // 2 x $4.50
->dividedBy(2) // 2 x $2.25
->multipliedBy(-3) // 2 x $-6.75
->abs(); // 2 x $6.75Please refer to brick/money's documentation for the full list of available features.
Nice to know: Whenever possible, you should prefer using modifiers to alter a price since its base value is meant to be constant. For more information on modifiers, please take at the "Adding modifiers" section below.
When creating a price object from a Brick\Money\Money instance, rounding errors can occur when doing division and multiplication.
An example of the problem: we have a base price of 1000 minor units, that we need to divide by 12 and then multiply by 11.
1000 / 12 * 11 = 916,6666666666...
Using the regular Brick\Money\Money class forces us to specify a rounding mode when doing the division, which means we have a rounded result before doing the multiplication, which introduces an error in the result:
use \Brick\Money\Money;
use \Whitecube\Price\Price;
use \Brick\Math\RoundingMode;
$base = Money::ofMinor(1000, 'EUR');
$price = new Price($base);
// A rounding mode is mandatory in order to do the division,
// which causes rounding errors down the line
$price->dividedBy(12, RoundingMode::HALF_UP)->multipliedBy(11);
$price->getMinorAmount(); // 913 minor units ❌The solution is to build the Price instance with a base Brick\Money\RationalMoney instance instead, which represents the amount as a fraction and thus does not require rounding.
use \Brick\Money\Money;
use \Whitecube\Price\Price;
use \Brick\Math\RoundingMode;
use \Brick\Money\Context\CustomContext;
$base = Money::ofMinor(1000, 'EUR')->toRational();
$price = new Price($base);
// With RationalMoney, rounding is not necessary at this stage
$price->dividedBy(12)->multipliedBy(11);
// But rounding can occur at the very end
$price->to(new CustomContext(2), RoundingMode::HALF_UP)->getMinorAmount(); // 917 minor units ✅For more information, see brick/money's documentation on the matter.
This package's default behavior is to consider its base price as the "per unit" price. When no units have been specified, it defaults to 1. Since "units" can be anything from a number of undividable products to a measurement, they are always converted to floats.
You can set the units amount (or "quantity" if you prefer) during instantiation:
use Whitecube\Price\Price;
use Brick\Money\Money;
$price = new Price(Money::ofMinor(500, 'EUR'), 2); // 2 units of €5.00 each
$same = Price::EUR(500, 2); // same result
$again = Price::parse('5.00', 'EUR', 2); // same result...or modify it later using the setUnits() method:
$price->setUnits(1.75); // 1.75 x €5.00You can return the units count using the units() method (always float):
$quantity = $price->units(); // 1.75VAT can be added by providing its relative value (eg. 21%):
use Whitecube\Price\Price;
$price = Price::USD(200); // 1 x $2.00
$price->setVat(21); // VANo open issues yet, or sync has not completed.