1
0
Fork 0
mirror of https://github.com/archtechx/money.git synced 2026-02-04 08:04:02 +00:00

feat: extract currency from the formatted string

This commit is contained in:
Gaurav 2022-03-10 11:39:53 +05:30
parent fa337d29b4
commit 93aeb2c300
4 changed files with 57 additions and 3 deletions

View file

@ -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.');
}
}