php – Method appears to be called twice-ThrowExceptions

Exception or error:

I have an application where users will enter accommodation details including the cost per night and then select the appropriate currency from a drop down. I am then using fixer.io to show the cost in both the currency it was entered in as well as converted to the user’s default currency.

The cost is stored in the database as an integer. I have methods convertToInteger and convertFromInteger that take the currency, look up how many subunits there are and do the appropriate math.

There is also a formatCurrency method to format according to currency. And a convertBetweenCurrency method for the actual conversion.

The convertFromInteger method is called inside the formatCurrency method.

The $cost_per_night_entered works fine and displays the correct amount and formatting. However, the $cost_per_night_user appears to be converted from Integer twice – it is always out by that unit. So, $148 is displayed as $1.48.

I’ve tried using Laravel’s fresh() and refresh() to no avail. Is this related to ‘nesting’ the calls together? I don’t think I’ve done something dumb like call it twice – but fresh eyes may prove otherwise 🙂

Controller show method:

$cost_per_night_entered = formatCurrency($accommodation->cost_per_night, $accommodation->currency, getLocale($accommodation->country));

$cost_per_night_user = formatCurrency(convertBetweenCurrency($accommodation->cost_per_night, $accommodation->currency, Auth::user()->currency), Auth::user()->currency, request()->server('HTTP_ACCEPT_LANGUAGE'));

Model methods:

function formatCurrency($amount, $currency_code, $locale)
{
$value = intval(convertFromInteger($amount, $currency_code));

$money = new Money\Money($value, new Money\Currency($currency_code));
$currencies = new Money\Currencies\ISOCurrencies();

$numberFormatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$moneyFormatter = new Money\Formatter\IntlMoneyFormatter($numberFormatter, $currencies);

return $moneyFormatter->format($money);
}



function convertBetweenCurrency($amount, $from_currency, $to_currency)
{
$endpoint = 'convert';
$access_key = 'xxx';

// initialize CURL:
$ch = curl_init('http://data.fixer.io/api/'.$endpoint.'? access_key='.$access_key.'&from='.$from_currency.'&to='.$to_currency.'&amount='.$amount.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// get the JSON data:
$json = curl_exec($ch);
curl_close($ch);

// Decode JSON response:
$conversionResult = json_decode($json, true);

// access the conversion result
return intval($conversionResult['result']);
}



function convertFromInteger($amount, $currency_code)
{
$currencies = PragmaRX\Countries\Package\Countries::currencies();

$currency = $currencies->where('iso.code', $currency_code)->toArray();

return $amount / (1 / $currency[$currency_code]['units']['minor']['majorValue']);
}
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *