php MoneyPHP Wrapper

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php MoneyPHP Wrapper相关的知识,希望对你有一定的参考价值。

<?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();
    }
}

以上是关于php MoneyPHP Wrapper的主要内容,如果未能解决你的问题,请参考以下文章

sh MoneyPHP Wrapper Helper的用法

Money PHP - 将 Money 对象保存在数据库中的无损方法

php [Medoo sql wrapper] Medoo mysql,sqlite,.. wrapper #php

PHP PHP Session Wrapper类

php Hashids Wrapper

PHP Tumblr API Wrapper