public function convert() { $validator = Validator::make(Input::all(), ['from' => 'required|min:3|max:3', 'to' => 'required|min:3|max:3']); if ($validator->fails()) { return response()->json([$validator->errors()])->setStatusCode(422, 'Validation Failed'); } $from = Currency::find(Input::get('from')); $to = Currency::find(Input::get('to')); $precision = (int) Config::get('laravel-currency.laravel-currency.precision'); $multiplier = pow(10, (int) Config::get('laravel-currency.laravel-currency.precision')); $amount = (double) Input::get('amount') ?: 1; if ($from == $to) { return response()->json($amount); } $amount = round($amount * $multiplier); if ($from && ($from->base == Input::get('to') || $from->base == $to->code)) { return response()->json(round($amount / $from->price, $precision)); } if ($to && ($to->base == Input::get('from') || $to->base == $from->code)) { return response()->json(round($amount * $to->price / pow($multiplier, 2), $precision)); } if (!$from || !$to) { return response()->json(['error' => Lang::get('currency.error.not_found')])->setStatusCode(404, 'Currency Not Found'); } if ($from->base !== $to->base) { throw new Exception('Cannot convert currencies with different bases.'); } return response()->json(round($amount / $from->price * $to->price / $multiplier, $precision)); }
public function synchronize() { $currencies = $this->fetch(); foreach ($currencies as $currency) { $this->convert($currency); } return Currency::all(); }