laxity7/phpmoney

Correct work with money (fiat and crypto) in PHP

1.0.2 2024-12-18 06:16 UTC

This package is auto-updated.

Last update: 2024-12-18 06:21:51 UTC


README

PHP library to make working with money with fiat and cryptocurrencies safer and easier!

License Latest Stable Version Total Downloads

Install

Install via composer

composer require laxity7/phpmoney

Requirements

This library requires the BCMath PHP extension.

Version 1.0.0 requires PHP 8.1+. For older version of PHP, use version 0.0.1 of this library, which requires PHP 7.4.

Features

  • Fiat and cryptocurrency support
  • JSON Serialization
  • String representation
  • Transparent calculation logic upon availability
  • Money formatting
  • Currency repositories (ISO currencies and TOP100 cryptocurrencies included)

Usage

Basic usage example:

use Laxity7\Money\Money;
use Laxity7\Money\Currency;

$tenEur = new Money(10.50, 'EUR');
//$tenEur = new Money(10.50, new Currency('EUR')); // the same as above
$twentyOneEur = $tenEur->add($tenEur);
echo $twentyOneEur->getAmount(); // 21
echo $twentyOneEur->getCurrency(); // EUR
echo $twentyOneEur; // 21 EUR
echo json_encode($twentyOneEur); // {"amount":"21","currency":"EUR"}

$btc = new Money(0.00000001, 'BTC');
$eth = new Money(1.01, 'USDT');
$sum = $btc->add($eth); // throws \Laxity7\Money\Exceptions\InvalidArgumentException

Configuration example:

use Laxity7\Money\Money;
use Laxity7\Money\MoneyConfig;

// You can configure your own currencies only once. You can't change it later.
// Scale is the number of decimal places in the currency (e.g. 2 for USD, 8 for BTC). Max is 14.
MoneyConfig::configure(
    new Currencies([
        ['name' => 'US Dollar', 'symbol' => 'USD', 'scale' => 2],
        ['name' => 'Euro', 'symbol' => 'EUR', 'scale' => 4],
        ['name' => 'MyCoin', 'symbol' => 'MC', 'scale' => 8],
   ]
);


//...
$tenEur = new Money(10.50, 'USD'); // ok
$tenMyCoin = new Money(10.50, 'MyCoin'); // ok
$tenBtc = new Money(10.50, 'BTC'); // throws \Laxity7\Money\Exceptions\UnacceptableCurrencyException

License

The MIT License (MIT). Please see License File for more information.