Files

48 lines
1.6 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Integer minor-unit money value object. No floats anywhere.
*/
final class Money {
/** Currencies with no minor unit (PayPal-supported subset). */
private const ZERO_DECIMAL = array( 'JPY', 'HUF', 'TWD' );
public function __construct( public readonly int $minor, public readonly string $currency ) {
if ( $minor < 0 ) {
throw new \InvalidArgumentException( 'Money cannot be negative.' );
}
}
public static function exponent( string $currency ): int {
return in_array( strtoupper( $currency ), self::ZERO_DECIMAL, true ) ? 0 : 2;
}
/** Parse a decimal string like "10.5" into minor units without float math. */
public static function fromDecimalString( string $amount, string $currency ): self {
$currency = strtoupper( $currency );
$exp = self::exponent( $currency );
if ( ! preg_match( '/^\d+(\.\d+)?$/', trim( $amount ) ) ) {
throw new \InvalidArgumentException( 'Invalid amount.' );
}
[ $whole, $frac ] = array_pad( explode( '.', trim( $amount ), 2 ), 2, '' );
if ( strlen( $frac ) > $exp ) {
throw new \InvalidArgumentException( 'Too many decimal places.' );
}
$frac = str_pad( $frac, $exp, '0' );
return new self( (int) ( $whole . $frac ), $currency );
}
/** Format as the decimal string PayPal expects, e.g. 1099 USD -> "10.99". */
public function toDecimalString(): string {
$exp = self::exponent( $this->currency );
if ( 0 === $exp ) {
return (string) $this->minor;
}
$s = str_pad( (string) $this->minor, 3, '0', STR_PAD_LEFT );
return substr( $s, 0, -2 ) . '.' . substr( $s, -2 );
}
}