Get historical currency exchange rates.

@param  \DateTime $date
@param  string    $base
@param  array     $targets
@return \Ultraleet\CurrencyRates\Contracts\Result
961426
public function historical($date, $base = 'EUR', $targets = [])
    {
        return $this->query($date->format('Y-m-d'), $base, $targets);
    }
174504
public function getTargetFromDate($date)
    {
        if (!preg_match('/^\d{4,14}$/', $date)) {
            throw new \InvalidArgumentException('Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].');
        }

        // what we need to append to the date according to the possible date string lengths
        $dateStrlenToAppend = [
            14 => '',
            12 => '00',
            10 => '0000',
            8 => '000000',
            6 => '01000000',
            4 => '0101000000',
        ];

        if (!isset($dateStrlenToAppend[strlen($date)])) {
            throw new \InvalidArgumentException('Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].');
        }

        $target = $date . $dateStrlenToAppend[strlen($date)];

        $dateTime = \DateTime::createFromFormat('YmdHis', $target);

        if ($dateTime === false) {
            throw new \InvalidArgumentException('Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].');
        }

        return $dateTime->format('YmdHis');
    }
6459
public function target($currencies)
    {
        if (!is_array($currencies)) {
            $currencies = [$currencies];
        }

        $this->targets = $currencies;

        return $this;
    }
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;
    }
1043190
public function dateIsLater(\DateTime $date) {
    $dateLater = FALSE;

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

    $t4 = $date->getTimestamp();

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

    return $dateLater;
  }
241111
public function get()
    {
        if ($this->date) {
            $result = $this->historical($this->date, $this->base, $this->targets);
        } else {
            $result = $this->latest($this->base, $this->targets);
        }

        // Ensure the result object is valid.
        if (!$result instanceof ResultContract) {
            throw new UnexpectedValueException('Invalid result type');
        }

        // Perform conversion if requested.
        if ($this->amount !== 1) {
            $converted = $result->rates;

            foreach ($converted as $key => $value) {
                $converted[$key] = round($this->amount * $value, 2);
            }

            // Attach converted values to results.
            $result->setConverted($converted);
        }

        return $result;
    }
1180984
private function convert($input): Rates
    {
        $rates = new Rates();
        $rates->timestamp = time();
        $rates->date = $this->date;
        $rates->base = 'USD';
        $rates->rates = [];
        $this->url = $this->url;

        $data = json_decode($input, true);

        if (!empty($data)) {
            if (isset($data['success'])) {
                if ($data['success']) {
                    $rates->extra['cl_timestamp'] = $data['timestamp'] ?? null;
                    $newrates = [];
                    if (isset($data['quotes']) and is_array($data['quotes'])) {
                        foreach ($data['quotes'] as $key => $row) {
                            if ($key === "$rates->base$rates->base") {
                                $key = $rates->base;
                            } else {
                                $key = str_replace($rates->base, '', $key);
                            }
                            $newrates[$key] = round($row, 5);
                        }
                    }
                }
            }
            if (isset($data['error'])) {
                $rates->extra['cl_error'] = $data['error'] ?? null;
            }
        }
        else {
            $rates->error = "No data in response from Currency Layer.";
        }

        if (!empty($newrates)) {
            $rates->rates = $newrates;
        }

        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;
    }
390224
def get_rate(self, currency, date):
        
        if str(currency) == defaults.INTERNAL_CURRENCY:
            return Decimal(1)

        cached = cache.get(_cache_key(currency, date))
        if cached:
            return Decimal(cached)
        else:
            # Expect self._get_rate() to implement caching
            return Decimal(self._get_rate(currency, date))
498177
private function getDistinctReferrersMetrics($date = false)
    {
        $propertyToAccessorMapping = array(
            'numberDistinctSearchEngines'  => 'getNumberOfDistinctSearchEngines',
            'numberDistinctSocialNetworks' => 'getNumberOfDistinctSocialNetworks',
            'numberDistinctKeywords'       => 'getNumberOfDistinctKeywords',
            'numberDistinctWebsites'       => 'getNumberOfDistinctWebsites',
            'numberDistinctWebsitesUrls'   => 'getNumberOfDistinctWebsitesUrls',
            'numberDistinctCampaigns'      => 'getNumberOfDistinctCampaigns',
        );

        $result = array();
        foreach ($propertyToAccessorMapping as $property => $method) {
            $result[$property] = $this->getNumericValue('Referrers.' . $method, $date);
        }
        return $result;
    }
1335160
public function rates(string $currency, string $date) : Rates
    {
        $rates = $this->getBaseRates($currency, $date);
        if (empty($rates)) {
            $rates = $this->convert($this->download($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;
    }
678063
private function convert($input) : Rates
    {
        $rates = new Rates();
        $rates->timestamp = time();
        $rates->date = $this->date;
        $rates->base = 'EUR';
        $rates->rates = [];
        $rates->url = $this->url;

        $data = json_decode($input, true);

        if (!empty($data)) {
            if (!empty($data['rates'])) {
                $rates->extra['fixer_date'] = $data['date'] ?? null;
                foreach ($data['rates'] as $key => $row) {
                    $rates->rates[$key] = $row;
                }
                //add 1:1 conversion rate from base for testing
                $rates->rates[$data['base']] = 1;
            }
        }
        else {
            $rates->error = "No data in response from Fixer.io";
        }

        return $rates;
    }
93763
def ecb(base, target):
    """"""
    api_url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
    resp = requests.get(api_url, timeout=1)
    text = resp.text

    def _find_rate(symbol):
        if symbol == 'EUR':
            return decimal.Decimal(1.00)
        m = re.findall(r"currency='%s' rate='([0-9\.]+)'" % symbol, text)
        return decimal.Decimal(m[0])

    return _find_rate(target) / _find_rate(base)
547924
def rate(self, from_currency, to_currency, date):
        """"""
        return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate(
            to_currency, date
        )
527371
protected function loadExchangeRates($targetCurrency)
    {
        if (!isset($this->exchangeRates[$targetCurrency])) {
            $currencyRates = $this->currencyRateRepository->findBy(['currencyTo' => $targetCurrency]);
            if (count($currencyRates) === 0) {
                throw new MissingCurrencyRatesException($targetCurrency);
            }
            foreach ($currencyRates as $rate) {
                $this->setExchangeRate($rate, $targetCurrency);
            }
        }
    }
856980
public function getByDate(string $date)
    {
        // Log Debug
        $this->flow->getLogger()->debug("Retrieving Settlement by Date $date");

        return $this->make(
            $this->performGet(
                'date',
                $date,
                [
                    'method' => 'getByDate',
                ]
            )
        );
    }
486003
public function get($date, $default = null)
    {
        if (!$this->has($date)) {
            return false;
        }
        return parent::get($date, $default);
    }