mirror of
https://github.com/archtechx/money.git
synced 2025-12-13 03:34:04 +00:00
feat: extract currency from the formatted string
This commit is contained in:
parent
fa337d29b4
commit
93aeb2c300
4 changed files with 57 additions and 3 deletions
|
|
@ -174,6 +174,10 @@ 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
|
||||
{
|
||||
$currency = isset($currency)
|
||||
? currency($currency)
|
||||
: PriceFormatter::extractCurrency($formatted);
|
||||
|
||||
$decimal = PriceFormatter::resolve($formatted, currency($currency), variadic_array($overrides));
|
||||
|
||||
return static::fromDecimal($decimal, currency($currency));
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ class PriceFormatter
|
|||
return $currency->prefix() . $decimal . $currency->suffix();
|
||||
}
|
||||
|
||||
/** Extract the decimal from the formatter string as per the currency's specifications. */
|
||||
/** Extract the decimal from the formatted string as per the currency's specifications. */
|
||||
public static function resolve(string $formatted, Currency $currency, array $overrides = []): float
|
||||
{
|
||||
$currency = Currency::fromArray(
|
||||
|
|
@ -41,4 +41,25 @@ class PriceFormatter
|
|||
|
||||
return (float) str_replace($currency->decimalSeparator(), '.', $removeNonDigits);
|
||||
}
|
||||
|
||||
/** Tries to extract the currency from the formatted string. */
|
||||
public static function extractCurrency(string $formatted): Currency
|
||||
{
|
||||
$possibleCurrency = null;
|
||||
|
||||
foreach (currencies()->all() as $currency) {
|
||||
if (
|
||||
str_starts_with($formatted, $currency->prefix())
|
||||
&& str_ends_with($formatted, $currency->suffix())
|
||||
) {
|
||||
if ($possibleCurrency) {
|
||||
throw new \Exception('Multiple currencies are using the same prefix and suffix. Please specify the currency of the formatted string.');
|
||||
}
|
||||
|
||||
$possibleCurrency = $currency;
|
||||
}
|
||||
}
|
||||
|
||||
return $possibleCurrency ?? throw new \Exception('None of the currencies are using the prefix and suffix that would match with the formatted string.');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue