1
0
Fork 0
mirror of https://github.com/archtechx/money.git synced 2025-12-12 19:34:02 +00:00

feature: money instance creation from a formatted string

This commit is contained in:
Gaurav 2022-03-09 12:50:04 +05:30
parent 8bdf0d1a2b
commit 38c6326a4d
4 changed files with 53 additions and 2 deletions

View file

@ -171,6 +171,14 @@ final class Money implements JsonSerializable, Arrayable, Wireable
]));
}
/** Create a Money instance from a formatted string. */
public static function fromFormatted(string $formatted, Currency|string $currency = null, mixed ...$overrides): self
{
$decimal = PriceFormatter::resolve($formatted, currency($currency), variadic_array($overrides));
return static::fromDecimal($decimal, currency($currency));
}
/** Get the string representation of the Money instance. */
public function __toString(): string
{

View file

@ -22,4 +22,19 @@ class PriceFormatter
return $currency->prefix() . $decimal . $currency->suffix();
}
/** Extract the decimal from the formatter string as per the currency's specifications. */
public static function resolve(string $formatted, Currency $currency, array $overrides = []): float
{
$currency = Currency::fromArray(
array_merge(currency($currency)->toArray(), $overrides)
);
$formatted = ltrim($formatted, $currency->prefix());
$formatted = rtrim($formatted, $currency->suffix());
$removeNonDigits = preg_replace('/[^\d'.preg_quote($currency->decimalSeparator()).']/', '', $formatted);
return (float) str_replace($currency->decimalSeparator(), '.', $removeNonDigits);
}
}