<?php
namespace CLNQCDRS\Utilities;
use Money\Currencies\ISOCurrencies;
use Money\Currency;
use Money\Formatter\DecimalMoneyFormatter;
use Money\Money as MoneyPHP;
use Money\Parser\DecimalMoneyParser;
/**
* Cast integers to MoneyPHP Instance
* MoneyPHP only accept integer
* @link http://moneyphp.org/en/latest/getting-started.html#accepted-integer-values
*/
class Money
{
/**
* Create Static Instance
* @return $this static instance
*/
public static function make()
{
return (new static );
}
/**
* Cast integer to MoneyPHP instance
* @param int $value value to cast in integer format
* @return \Money\Money MoneyPHP Instance
*/
public function castMoney(int $value): MoneyPHP
{
return (new MoneyPHP($value, new Currency(config('currency.swift_code'))));
}
/**
* Convert integer money to human readable format
* @param int $value Integer money representation
* @return string Return readable format for human
*/
public function toHuman(int $value): string
{
return config('currency.label') . ' ' . self::toCommon($value, true);
}
/**
* Convert integer money to common view for the system
* Instead of 700000, to 7000
* @param int $value Integer money representation
* @return string Return readable format for human
*/
public function toCommon(int $value, $format = false): string
{
$money = $this->castMoney($value);
$currencies = new ISOCurrencies();
$moneyFormatter = new DecimalMoneyFormatter($currencies);
if ($format) {
// use for read-only
return number_format($moneyFormatter->format($money), 2, '.', ',');
} else {
// use for read-and-write
return $moneyFormatter->format($money);
}
}
/**
* Return to Database Format.
* This method intended to be use before save to the database
* and this need to be call manually.
* @param string $value
* @param string $swift_code
* @return int
*/
public function toMachine(string $value, string $swift_code = ''): int
{
$currencies = new ISOCurrencies();
$moneyParser = new DecimalMoneyParser($currencies);
$swift_code = empty($swift_code) ? config('currency.swift_code') : $swift_code;
$money = $moneyParser->parse($value, $swift_code);
return $money->getAmount();
}
}