/** * Return exchange rates from $from to $to * * @param string $fromCode ISO code of source currency * @param string|array $toCodes ISO code of target currency, or array with ISO codes of targets * * @return array in the form of 'ISOCODE' => (float) exchange rate */ public function getExchangeRates($fromCode, $toCodes = array()) { if (!is_array($toCodes)) { $toCodes = array($toCodes); } if (empty($this->exchangeRates)) { $this->exchangeRates = $this->exchangeRatesAdapter->getExchangeRates(); } if (empty($this->exchangeRates)) { return []; } $baseExchangeRate = $this->exchangeRates[$fromCode]; $exchangeRates = array(); foreach ($toCodes as $code) { $exchangeRates[$code] = $this->exchangeRates[$code] / $baseExchangeRate; } return $exchangeRates; }
/** * Populates the exchange rates. * * @return $this Self object */ public function populate() { $currenciesCodes = []; $currencies = $this->currencyRepository->findAll(); /** * Create an array of all active currency codes. * * @var CurrencyInterface $currency */ foreach ($currencies as $currency) { if ($currency->getIso() != $this->defaultCurrency) { $currenciesCodes[] = $currency->getIso(); } } /** * Get rates for all of the enabled and active currencies. */ $rates = $this->currencyExchangeRatesAdapter->getExchangeRates($this->defaultCurrency, $currenciesCodes); /** * @var CurrencyInterface $sourceCurrency */ $sourceCurrency = $this->currencyRepository->findOneBy(['iso' => $this->defaultCurrency]); /** * [ * "EUR" => "1,378278", * "YEN" => "0,784937", * ]. */ foreach ($rates as $code => $rate) { /** * @var CurrencyInterface $targetCurrency */ $targetCurrency = $this->currencyRepository->findOneBy(['iso' => $code]); if (!$targetCurrency instanceof CurrencyInterface) { continue; } /** * check if this is a new exchange rate, or if we have to * create a new one. */ $exchangeRate = $this->currencyExchangeRateObjectDirector->findOneBy(['sourceCurrency' => $sourceCurrency, 'targetCurrency' => $targetCurrency]); if (!$exchangeRate instanceof CurrencyExchangeRateInterface) { $exchangeRate = $this->currencyExchangeRateObjectDirector->create(); } $exchangeRate->setExchangeRate($rate)->setSourceCurrency($sourceCurrency)->setTargetCurrency($targetCurrency); $this->currencyExchangeRateObjectDirector->save($exchangeRate); } return $this; }