Get historical currency exchange rates.

@param  \DateTime $date
@param  string    $base
@param  array     $targets
@return \Ultraleet\CurrencyRates\Contracts\Result
198622
public function historical($date, $base = 'EUR', $targets = [])
    {
        $key = array_search($base, $this->currencies);
        if ($key === false) {
            throw new InvalidArgumentException("Invalid base currency specified: $base");
        }

        if (empty($targets)) {
            $currencies = $this->currencies;
            unset($currencies[$key]);
        } else {
            $currencies = $targets;
        }

        // generate dummy results
        $res = [];
        foreach ($currencies as $currency) {
            if (!in_array($currency, $this->currencies)) {
                throw new InvalidArgumentException("Invalid target currency specified: $currency");
            }

            $res[$currency] = mt_rand(10000, 150000) / 100000;
        }

        // return the results
        return new Result($base, $date, $res);
    }
81159
public static function getSaleStats(\DateTime $startDate, \DateTime $endDate, $includeShipping, $withTaxes = true)
    {
        $amount = floatval(
            self::baseSaleStats($startDate, $endDate, 'o')
                ->innerJoinOrderProduct()
                ->withColumn("SUM((`order_product`.QUANTITY * IF(`order_product`.WAS_IN_PROMO,`order_product`.PROMO_PRICE,`order_product`.PRICE)))", 'TOTAL')
                ->select(['TOTAL'])
                ->findOne()
        );

        if ($withTaxes) {
            $amount += floatval(
                self::baseSaleStats($startDate, $endDate, 'o')
                    ->useOrderProductQuery()
                        ->useOrderProductTaxQuery()
                            ->withColumn("SUM((`order_product`.QUANTITY * IF(`order_product`.WAS_IN_PROMO,`order_product_tax`.PROMO_AMOUNT,`order_product_tax`.AMOUNT)))", 'TAX')
                        ->endUse()
                    ->endUse()
                    ->select(['TAX'])
                    ->findOne()
            );
        }

        $amount -= floatval(
            self::baseSaleStats($startDate, $endDate)
                ->withColumn("SUM(`order`.discount)", 'DISCOUNT')
                ->select('DISCOUNT')
                ->findOne()
        );

        if ($includeShipping) {
            $amount += floatval(
                self::baseSaleStats($startDate, $endDate)
                    ->withColumn("SUM(`order`.postage)", 'POSTAGE')
                    ->select('POSTAGE')
                    ->findOne()
            );
        }

        return $amount;
    }
5207
public function getRateModel($base = null, $date = null) : Rates
    {
        $base = strtoupper($base);
        if (empty($base)) {
            $base = 'USD';
        }
        if (empty($date)) {
            $date = date('Y-m-d');
        }
        $this->fromCache = false;
        $api = $this->api;

        if ($this->cacheEnabled) {
            $cachekey = "cc-$api-$base-$date";

            $rates = Cache::get($cachekey);
            if (is_object($rates) and isset($rates->rates)) {
                $this->fromCache = true;
                if ($this->logEnabled) {
                    Log::debug("Got currency rates from cache: $cachekey");
                }
            }
            else {
                $rates = $this->provider->rates($base, $date);
                if (!empty($rates->rates)) {
                    if(Cache::add($cachekey, $rates, $this->cacheMinutes) and $this->logEnabled) {
                        Log::debug('Added new currency rates to cache: '.$cachekey.' for '.$this->cacheMinutes.' min.');
                    }
                }
            }
        }
        else {
            $rates = $this->provider->rates($base, $date);
        }

        if (empty($rates->rates)) {
            Log::warning("$rates->error -> $rates->url");
        }

        return $rates;
    }
230088
private function resolveCurrencies(array $currencies, string $baseCurrency): array
    {
        if (empty($currencies)) {
            return [$baseCurrency];
        }

        if (!in_array($baseCurrency, $currencies)) {
            $currencies[] = $baseCurrency;
        }

        return $currencies;
    }
976133
public function getFor(Currency $currency): float
    {
        if ($currency->equals($this->baseCurrency)) {
            // no need to make an api call for same currencies.
            $this->exchangeRates[$currency->getCode()] = (float) 1;
        } else {
            $this->retrieveExchangeRateFor($currency);
        }

        return $this->exchangeRates[$currency->getCode()];
    }
411120
public function rates(string $currency, string $date = null) : Rates
    {
        $rates = $this->getBaseRates($currency, $date);
        if (empty($rates)) {
            if ($this->settings['fixer-use-real-base']) {
                $base = strtoupper($currency);
            }
            else {
                $base = 'EUR';
            }
            $rates = $this->convert($this->download($base, $date));
            if ($currency !== 'EUR') {
                //Set USD base rate
                $this->setBaseRates($rates->convertBaseRatesToUSD());

                if ($currency !== 'USD') {
                    $rates = $rates->convertBaseRateToCurrency($currency);
                    $this->setBaseRates($rates);
                }
            }
            else {
                $this->setBaseRates($rates);
            }
        }

        return $rates;
    }
465310
public function getChangedProperties(\DateTime $date)
    {
        $properties = array();

        $xml = $this->execute(sprintf('property/%s', $date->format('Y/m/d/H/i/s')));

        foreach ($xml->property as $xmlProperty) {
            $property = new ChangedPropertySummary;
            $property->setPropId(self::normalise($xmlProperty->propid, 'int'));
            $property->setLastChanged(self::normalise($xmlProperty->lastchanged, 'datetime'));
            $property->setLastAction(self::normalise($xmlProperty->action, 'string'));
            $property->setUrl(self::normalise($xmlProperty->url, 'string'));
            $properties[] = $property;
        }

        return $properties;
    }
1094747
public function findDeprecatedTranslationsBeforeDate(DateTime $date, $domain)
    {
        $qb = $this->createQueryBuilder('t');
        $result = $qb->select('t')
            ->where('t.status = :status')
            ->andWhere('t.domain = :domain')
            ->andWhere('t.updatedAt < :date')
            ->setParameter('status', Translation::STATUS_DEPRECATED)
            ->setParameter('domain', $domain)
            ->setParameter('date', $date)
            ->getQuery()
            ->getResult();

        return $result;
    }
1287362
public function getRate($source, $target)
    {

        $provider = env('FOREX_PROVIDER');
        $url = env('FOREX_PROVIDER_URL');
        $key = env('FOREX_PROVIDER_KEY', '');
        $cache_minutes = intval(env('FOREX_CACHE_MINUTES', 720));

        if ((! $provider) || (! $url))
            throw new ForexException('Invalid exchange rate provider configuration.');

        if(! in_array($source, $this->currency_codes))
            throw new ForexException('Invalid source currency code.');

        if(! in_array($target, $this->currency_codes))
            throw new ForexException('Invalid target currency code.');

        $conversion = $source.$target;
        
        if (($cache_minutes > 0) && (Cache::has($conversion)))
            $rate = Cache::get($conversion);
        else {

            $provider_class = 'Viewflex\Forex\Providers\\' . $provider;

            if (! class_exists($provider_class))
                throw new ForexException("\"" . $provider . "\" is not a supported provider.");

            $this->service = new $provider_class($url, $key, $cache_minutes);
            $rate = $this->service->getRate($source, $target);
            
            if($rate <= 0)
                throw new ForexException('Error retrieving exchange rate.');

            if ($cache_minutes > 0) {
                if(! Cache::add($conversion, $rate, Carbon::now()->addMinutes($cache_minutes)))
                    throw new ForexException('Unable to add exchange rate to cache.');
            }
            
        }

        return $rate;
    }
546345
private function doCreateRate(ExchangeRateQuery $exchangeQuery, DateTimeInterface $requestedDate): ExchangeRate
    {
        $currencyPair = $exchangeQuery->getCurrencyPair();
        $content = $this->request($this->buildUrl($requestedDate));

        $lines = explode("\n", $content);

        if (!$date = \DateTime::createFromFormat(self::DATE_FORMAT, $this->parseDate($lines[0]))) {
            throw new UnsupportedCurrencyPairException($currencyPair, $this);
        }

        $date->setTime(0, 0, 0);
        foreach (array_slice($lines, 2) as $line) {
            if (!preg_match(self::CURRENCY_LINE_PATTERN, $line)) {
                continue;
            }
            list(, , $count, $code, $rate) = explode('|', $line);

            if ($code === $currencyPair->getBaseCurrency()) {
                $rate = (float) str_replace(',', '.', $rate);

                return $this->createRate($currencyPair, (float) ($rate / (int) $count), $date);
            }
        }

        throw new UnsupportedCurrencyPairException($currencyPair, $this);
    }
1132549
protected function getHistoricalExchangeRate(HistoricalExchangeRateQuery $exchangeQuery): ExchangeRateContract
    {
        $historicalDateTime = $this->getAdoptedDateTime($exchangeQuery->getDate());

        if ($this->isEnterprise()) {
            $url = sprintf(
                self::ENTERPRISE_HISTORICAL_URL,
                $this->stringifyCurrencyPair($exchangeQuery->getCurrencyPair()),
                $historicalDateTime->format('Y-m-d'),
                $this->options['access_key']
            );
        } else {
            $url = sprintf(
                self::FREE_HISTORICAL_URL,
                $this->stringifyCurrencyPair($exchangeQuery->getCurrencyPair()),
                $historicalDateTime->format('Y-m-d'),
                $this->options['access_key']
            );
        }

        return $this->fetchOnlineRate($url, $exchangeQuery);
    }
1043190
public function dateIsLater(\DateTime $date) {
    $dateLater = FALSE;

    $t2 = $this->end_date->getTimeStamp();

    $t4 = $date->getTimestamp();

    if ($t2 < $t4) {
      $dateLater = TRUE;
    }

    return $dateLater;
  }
1272200
public function baseConvert(array $source, int $sourceBase, int $targetBase): array
    {
        $result = [];
        while ($count = count($source)) {
            $quotient = [];
            $remainder = "0";
            $sourceBase = (string) $sourceBase;
            $targetBase = (string) $targetBase;
            for ($i = 0; $i !== $count; $i++) {
                $accumulator = bcadd((string) $source[$i], bcmul($remainder, $sourceBase));
                $digit = bcdiv($accumulator, $targetBase, 0);
                $remainder = bcmod($accumulator, $targetBase);
                if (count($quotient) || $digit) {
                    array_push($quotient, $digit);
                };
            }
            array_unshift($result, $remainder);
            $source = $quotient;
        }

        return $result;
    }
917048
public function formatPrice(float $price, $baseCurrency = null, $targetCurrency = null, $locale = null, $quantity = 1) : string
    {
        return $this->helper->convertAndFormat($price, $baseCurrency, $targetCurrency, $quantity, $locale);
    }
1246579
public function getRateResults($base = null, $date = null) : array
    {
        $rates = $this->getRateModel($base, $date);

        return $rates->rates;
    }
222045
public function getExchangeRate()
    {
        try {
            $currentCurrency = $this->storeManager->getStore()->getCurrentCurrency()->getCode();
            $baseCurrency = $this->storeManager->getStore()->getBaseCurrency()->getCode();
            return (float)$this->currencyFactory->create()->load($baseCurrency)->getAnyRate($currentCurrency);
        } catch (\Exception $e) {
            throw $e;
        }
    }
1296150
def calculate_rates(base_currency, counter_currency, forward_rate=None, fwd_points=None, spot_reference=None):
    """"""
    if base_currency not in DIVISOR_TABLE:
        divisor = DIVISOR_TABLE.get(counter_currency, DEFAULT_DIVISOR)
        if forward_rate is None and fwd_points is not None and spot_reference is not None:
            forward_rate = spot_reference + fwd_points / divisor
        elif forward_rate is not None and fwd_points is None and spot_reference is not None:
            fwd_points = (forward_rate - spot_reference) * divisor
        elif forward_rate is not None and fwd_points is not None and spot_reference is None:
            spot_reference = forward_rate - fwd_points / divisor

    rates = {}
    if forward_rate is not None:
        rates['forward_rate'] = forward_rate

    if fwd_points is not None:
        rates['fwd_points'] = fwd_points

    if spot_reference is not None:
        rates['spot_reference'] = spot_reference

    return rates