public function getRates(Currency $base)
 {
     $rates = (array) Request::get(sprintf('http://api.fixer.io/latest?base=%s', $base->getName()))->send()->body->rates;
     $ret = [];
     foreach ($rates as $key => $rate) {
         $ret[$key] = $rate;
     }
     return $ret;
 }
示例#2
0
 /**
  * {@inheritdoc}
  */
 public function subunitFor(Currency $currency)
 {
     if ($currency->getCode() !== self::CODE) {
         throw new UnknownCurrencyException($currency->getCode() . ' is not bitcoin and is not supported by this currency repository');
     }
     return 8;
 }
示例#3
0
 /**
  * {@inheritdoc}
  */
 public function quote(Currency $baseCurrency, Currency $counterCurrency)
 {
     if (isset($this->list[$baseCurrency->getCode()][$counterCurrency->getCode()])) {
         return new CurrencyPair($baseCurrency, $counterCurrency, $this->list[$baseCurrency->getCode()][$counterCurrency->getCode()]);
     }
     throw UnresolvableCurrencyPairException::createFromCurrencies($baseCurrency, $counterCurrency);
 }
 public function getCurrencyPair(Currency $counterCurrency, Currency $baseCurrency)
 {
     $from = $counterCurrency->getName();
     $to = $baseCurrency->getName();
     $pair = null;
     $url = self::URL . sprintf(self::QUERY, $from, $to);
     $html = @file_get_contents($url);
     if ($html == false) {
         throw new CurrencyRateException('Rate not avaiable, resource not found');
     }
     $doc = new \DOMDocument();
     @$doc->loadHTML($html);
     $el = $doc->getElementById('currency_converter_result');
     if ($el && $el->hasChildNodes()) {
         foreach ($el->childNodes as $node) {
             if ($node->nodeName == 'span' && preg_match('/[0-9\\.]+ ' . $to . '/i', $node->textContent, $matches)) {
                 $ratio = (double) $matches[0];
                 $pair = new CurrencyPair($counterCurrency, $baseCurrency, $ratio);
             }
         }
     }
     if (!$pair) {
         throw new CurrencyRateException('Rate not avaiable, can not parse result: ' . $html);
     }
     return $pair;
 }
 public function getRate(Currency $from, Currency $to, DateTime $date = null)
 {
     $rates = $this->getRatesFromStore($date);
     $dollarFrom = $from->getName() == 'USD' ? 1.0 : $rates[$from->getName()];
     $dollarTo = $to->getName() == 'USD' ? 1.0 : $rates[$to->getName()];
     $rate = $dollarFrom / $dollarTo;
     return new CurrencyPair($from, $to, $rate);
 }
示例#6
0
 /**
  * {@inheritdoc}
  */
 public function quote(Currency $baseCurrency, Currency $counterCurrency)
 {
     try {
         $rate = $this->swap->latest($baseCurrency->getCode() . '/' . $counterCurrency->getCode());
     } catch (ExchangerException $e) {
         throw UnresolvableCurrencyPairException::createFromCurrencies($baseCurrency, $counterCurrency);
     }
     return new CurrencyPair($baseCurrency, $counterCurrency, $rate->getValue());
 }
 private function getRates(Currency $currency)
 {
     $rates = $this->pool->getItem($currency->getName());
     if ($rates->isMiss()) {
         $newRates = $this->rates->getRates($currency);
         $rates->set($newRates, $this->ttl);
     }
     return $newRates;
 }
示例#8
0
 /**
  * {@inheritdoc}
  */
 public function subunitFor(Currency $currency)
 {
     if (null === self::$currencies) {
         self::$currencies = $this->loadCurrencies();
     }
     if (!isset(self::$currencies[$currency->getCode()])) {
         throw new UnknownCurrencyException('Cannot find ISO currency ' . $currency->getCode());
     }
     return self::$currencies[$currency->getCode()]['minorUnit'];
 }
示例#9
0
 /**
  * {@inheritdoc}
  */
 public function getCurrencyPair(Currency $baseCurrency, Currency $counterCurrency)
 {
     $swapCurrencyPair = new SwapCurrencyPair($baseCurrency->getCode(), $counterCurrency->getCode());
     try {
         $rate = $this->swap->quote($swapCurrencyPair);
     } catch (SwapException $e) {
         throw UnresolvableCurrencyPairException::createFromCurrencies($baseCurrency, $counterCurrency);
     }
     return new CurrencyPair($baseCurrency, $counterCurrency, $rate->getValue());
 }
 /**
  * Retrieves exchange rates from http://fixer.io
  *
  * @param Currency $currency
  */
 private function retrieveExchangeRateFor(Currency $currency)
 {
     $response = $this->client->request('GET', self::EXCHANGE_RATE_API_URL . '/latest', ['query' => ['base' => $this->baseCurrency->getName()]]);
     Assert::same($response->getStatusCode(), 200);
     $rawExchangeRates = $response->getBody();
     $exchangeRates = json_decode($rawExchangeRates, true);
     Assert::isArray($exchangeRates);
     Assert::keyExists($exchangeRates, 'rates');
     Assert::keyExists($exchangeRates['rates'], $currency->getName());
     Assert::numeric($exchangeRates['rates'][$currency->getName()]);
     $this->exchangeRates[$currency->getName()] = $exchangeRates['rates'][$currency->getName()];
 }
示例#11
0
 /**
  * {@inheritdoc}
  */
 public function subunitFor(Currency $currency)
 {
     $item = $this->pool->getItem('currency|subunit|' . $currency->getCode());
     if (false === $item->isHit()) {
         $item->set($this->currencies->subunitFor($currency));
         if ($item instanceof TaggableItemInterface) {
             $item->addTag('currency.subunit');
         }
         $this->pool->save($item);
     }
     return $item->get();
 }
 /**
  * Retrieves exchange rates from http://free.currencyconverterapi.com
  *
  * @param Currency $currency
  */
 private function retrieveExchangeRateFor(Currency $currency)
 {
     $conversion = sprintf('%s_%s', $currency->getName(), $this->baseCurrency->getName());
     $response = $this->client->request('GET', self::EXCHANGE_RATE_API_URL . '/api/v3/convert', ['query' => ['q' => $conversion]]);
     Assert::same($response->getStatusCode(), 200);
     $rawExchangeRates = $response->getBody();
     $exchangeRates = json_decode($rawExchangeRates, true);
     Assert::isArray($exchangeRates);
     Assert::keyExists($exchangeRates, 'results');
     Assert::keyExists($exchangeRates['results'], $conversion);
     Assert::keyExists($exchangeRates['results'][$conversion], 'val');
     Assert::numeric($exchangeRates['results'][$conversion]['val']);
     $this->exchangeRates[$currency->getName()] = (double) $exchangeRates['results'][$conversion]['val'];
 }
 public function getCurrencyPair(Currency $counterCurrency, Currency $baseCurrency)
 {
     $from = $counterCurrency->getName();
     $to = $baseCurrency->getName();
     $pair = null;
     $result = file_get_contents(sprintf(self::URL, $from, $to, $this->key));
     $result = json_decode($result);
     if ($result && isset($result->rate)) {
         $pair = new CurrencyPair($counterCurrency, $baseCurrency, $result->rate);
     }
     if ($pair == null) {
         throw new CurrencyRateException('Rate not avaiable, missing in result');
     }
     return $pair;
 }
示例#14
0
文件: Sums.php 项目: krvd/cms-Inji
 function __toString()
 {
     $string = '';
     $first = true;
     foreach ($this->sums as $currency_id => $sum) {
         if ($first) {
             $first = false;
         } else {
             $string .= '<br />';
         }
         $string .= '<span style="white-space:nowrap;">';
         $string .= number_format($sum, 2, '.', ' ');
         if (\App::$cur->money) {
             $currency = \Money\Currency::get($currency_id);
             if ($currency) {
                 $string .= ' ' . $currency->acronym();
             } else {
                 $string .= ' руб.';
             }
         } else {
             $string .= ' руб.';
         }
         $string .= '</span>';
     }
     return $string;
 }
示例#15
0
 /**
  * @inheritdoc
  */
 public function getRelativeRatio($referenceCurrencyCode, $currencyCode)
 {
     $currency = new Currency($currencyCode);
     $referenceCurrency = new Currency($referenceCurrencyCode);
     if ($currencyCode === $referenceCurrencyCode) {
         return (double) 1;
     }
     $ratioList = $this->storage->loadRatioList();
     if (!array_key_exists($currency->getName(), $ratioList)) {
         throw new MoneyException("unknown ratio for currency {$currencyCode}");
     }
     if (!array_key_exists($referenceCurrency->getName(), $ratioList)) {
         throw new MoneyException("unknown ratio for currency {$referenceCurrencyCode}");
     }
     return $ratioList[$currency->getName()] / $ratioList[$referenceCurrency->getName()];
 }
 public function getCurrencyPair(Currency $counterCurrency, Currency $baseCurrency)
 {
     $from = $counterCurrency->getName();
     $to = $baseCurrency->getName();
     $pair = null;
     $url = self::URL . sprintf(self::QUERY, $from, $to);
     $csv = @file_get_contents($url);
     if ($csv == false) {
         throw new CurrencyRateException('Rate not avaiable, resource not found');
     }
     if (preg_match('/"' . $to . '",([0-9\\.]+)/i', $csv, $matches)) {
         if ($matches && isset($matches[1])) {
             $ratio = (double) $matches[1];
         } else {
             throw new CurrencyRateException('Rate not avaiable, can not parse result: ' . $csv);
         }
         $pair = new CurrencyPair($counterCurrency, $baseCurrency, $ratio);
     } else {
         throw new CurrencyRateException('Rate not avaiable, can not parse result: ' . $csv);
     }
     return $pair;
 }
示例#17
0
 /**
  * Extracts a formatted money string.
  * @example echo Money::USD(500)->formattedString();
  * @return string
  */
 public function formattedString()
 {
     $decimal_separator = $this->currency->getDecimals();
     $thousand_separator = $this->currency->getThousands();
     $multiplier = $this->currency->getMultiplier();
     $decimals = (int) log10($multiplier);
     $number = $this->getAmount() / $multiplier;
     $value = '';
     $prefix = '';
     $suffix = '';
     if ($number < 0) {
         $prefix .= '-';
         $number = -$number;
     }
     $value .= number_format($number, $decimals, $decimal_separator, $thousand_separator);
     if ($this->currency->hasSymbolFirst()) {
         $prefix .= $this->currency->getSymbol();
     } else {
         $suffix .= $this->currency->getSymbol();
     }
     return $prefix . $value . $suffix;
 }
 /**
  * @param Currency $referenceCurrency
  * @param Currency $currency
  *
  * @return string The yahoo finance endpoint to get Currency exchange rate
  */
 protected function getEndpoint(Currency $referenceCurrency, Currency $currency)
 {
     return 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22' . $referenceCurrency->getName() . $currency->getName() . '%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
 }
 public function getRates(Currency $base)
 {
     return $this->rates[$base->getName()];
 }
示例#20
0
 /**
  * @return string
  */
 public function getCurrencySymbol()
 {
     return Intl::getCurrencyBundle()->getCurrencySymbol($this->currency->getName(), $this->locale);
 }
示例#21
0
 public function exchangeAction()
 {
     $wallets = $this->module->getUserWallets();
     $currency = !empty($_GET['currency_id']) ? \Money\Currency::get((int) $_GET['currency_id']) : null;
     if ($currency && empty($wallets[$currency->id])) {
         $currency = null;
     }
     $targetCurrency = !empty($_GET['target_currency_id']) ? \Money\Currency::get((int) $_GET['target_currency_id']) : null;
     if ($targetCurrency && empty($wallets[$targetCurrency->id])) {
         $targetCurrency = null;
     }
     $where = [];
     if ($currency) {
         $where[] = ['currency_id', $currency->id];
     } else {
         $where[] = ['currency_id', implode(',', array_keys($wallets)), 'IN'];
     }
     if ($targetCurrency) {
         $where[] = ['target_currency_id', $targetCurrency->id];
     } else {
         $where[] = ['target_currency_id', implode(',', array_keys($wallets)), 'IN'];
     }
     if ($where) {
         $rates = Money\Currency\ExchangeRate::getList(['where' => $where]);
     } else {
         $rates = [];
     }
     if (!empty($_GET['exchange']) && $currency && $targetCurrency && !empty($rates[$_GET['exchange']['rate_id']])) {
         $error = false;
         $rate = $rates[$_GET['exchange']['rate_id']];
         if (empty($_GET['exchange']['give']['amount']) || !(double) $_GET['exchange']['give']['amount']) {
             Msg::add('Укажите сумму которую вы хотите отдать');
             $error = true;
         } else {
             $amount = (double) $_GET['exchange']['give']['amount'];
         }
         if (!empty($amount) && $amount > $wallets[$currency->id]->amount) {
             Msg::add('Вы указали сумму большую чем вам доступно');
             $error = true;
         }
         if (!$error) {
             $wallets[$currency->id]->diff(-$amount, 'Обмен валюты на ' . $targetCurrency->name());
             $wallets[$targetCurrency->id]->diff($amount * $rate->rate, 'Обмне валюты с ' . $currency->name());
             Tools::redirect('/users/cabinet', 'Обмен был успешно проведен');
         }
     }
     $this->view->setTitle('Обмен валюты');
     $this->view->page(['data' => compact('rates', 'currency', 'targetCurrency', 'wallets')]);
 }
 /**
  * @param Currency $referenceCurrency
  * @param Currency $currency
  *
  * @return string The yahoo finance endpoint to get Currency exchange rate
  */
 protected function getEndpoint(Currency $referenceCurrency, Currency $currency)
 {
     $q = sprintf('select * from yahoo.finance.xchange where pair in ("%s%s")', $referenceCurrency->getName(), $currency->getName());
     $queryString = http_build_query(array('q' => $q, 'format' => 'json', 'env' => 'store://datatables.org/alltableswithkeys'));
     return 'https://query.yahooapis.com/v1/public/yql?' . $queryString;
 }
示例#23
0
文件: Money.php 项目: NGWNGW/money
 /**
  * @param \Money\Money $other
  * @return bool
  */
 public function isSameCurrency(Money $other)
 {
     return $this->currency->equals($other->currency);
 }
示例#24
0
 /**
  * {@inheritdoc}
  */
 public function configureOptions(OptionsResolver $resolver)
 {
     $resolver->setDefaults(['currency' => $this->currency->getName()]);
 }
示例#25
0
<?php

return ['name' => 'Валюта', 'params' => ['currency_id' => ['type' => 'select'], 'type' => ['type' => 'select', 'source' => 'array', 'sourceArray' => ['procent' => 'Процент', 'amount' => 'Кол-во']], 'amount' => ['type' => 'decimal']], 'viewer' => function ($level) {
    $levelTypes = ['procent' => 'Процент', 'amount' => 'Сумма'];
    return $levelTypes[$level->params['type']->value] . ': ' . $level->params['amount']->value . ' ' . ($level->params['type']->value == 'procent' ? '%' : ($level->params['currency_id']->value ? \Money\Currency::get($level->params['currency_id']->value)->acronym() : ''));
}, 'rewarder' => function ($reward, $sums, $user, $rootUser, $level, $rewardGet) {
    $wallets = \App::$cur->money->getUserWallets($user->id);
    $amount = 0;
    if (!empty($wallets[$level->params['currency_id']->value])) {
        switch ($level->params['type']->value) {
            case 'procent':
                $finalSum = 0;
                foreach ($sums as $currency_id => $sum) {
                    if ($currency_id != $level->params['currency_id']->value) {
                        $rate = \Money\Currency\ExchangeRate::get([['currency_id', $currency_id], ['target_currency_id', $level->params['currency_id']->value]]);
                        if ($rate) {
                            $finalSum += $sum * $rate->rate;
                        }
                    } else {
                        $finalSum += $sum;
                    }
                }
                switch ($reward->round_type) {
                    case 'round':
                        $finalSum = round($finalSum, $reward->round_precision);
                        $amount = $finalSum / 100 * (double) $level->params['amount']->value;
                        break;
                    case 'floor':
                        $finalSum = floor($finalSum);
                        $amount = $finalSum / 100 * (double) $level->params['amount']->value;
                        break;
示例#26
0
 public function bonusTrigger($event)
 {
     $cart = $event['eventObject'];
     foreach ($cart->cartItems as $cartItem) {
         foreach ($cartItem->price->offer->bonuses as $bonus) {
             if ($bonus->limited && $bonus->left <= 0) {
                 continue;
             } elseif ($bonus->limited && $bonus->left > 0) {
                 $bonus->left -= 1;
                 $bonus->save();
             }
             switch ($bonus->type) {
                 case 'currency':
                     $currency = \Money\Currency::get($bonus->value);
                     $wallets = App::$cur->money->getUserWallets($cart->user->id);
                     $wallets[$currency->id]->diff($bonus->count, 'Бонус за покупку');
                     break;
             }
         }
     }
     return $cart;
 }
示例#27
0
?>
</ul>
<div class="tab-content">
  <div role="tabpanel" class="tab-pane fade in active" id="home">
    <?php 
$form = new Ui\Form();
$form->begin();
$form->input('checkbox', 'config[view_empty_warehouse]', 'Показывать отсутствующие товары', ['value' => App::$cur->ecommerce->config['view_empty_warehouse']]);
$form->input('checkbox', 'config[view_empty_image]', 'Показывать товары без изображения', ['value' => App::$cur->ecommerce->config['view_empty_image']]);
$form->input('checkbox', 'config[sell_empty_warehouse]', 'Продавать отсутствующие товары', ['value' => App::$cur->ecommerce->config['sell_empty_warehouse']]);
$form->input('checkbox', 'config[sell_over_warehouse]', 'Продавать сверх остатоков на складе', ['value' => App::$cur->ecommerce->config['sell_over_warehouse']]);
$form->input('checkbox', 'config[show_zero_price]', 'Показывать товары с нулевой ценой', ['value' => App::$cur->ecommerce->config['show_zero_price']]);
$form->input('checkbox', 'config[show_without_price]', 'Показывать товары без цен', ['value' => App::$cur->ecommerce->config['show_without_price']]);
$form->input('select', 'config[defaultCategoryView]', 'Стандартный вид категории', ['value' => App::$cur->ecommerce->config['defaultCategoryView'], 'values' => App::$cur->ecommerce->viewsCategoryList()]);
if (App::$cur->money) {
    $form->input('select', 'config[defaultCurrency]', 'Валюта по умолчанию', ['value' => App::$cur->ecommerce->config['defaultCurrency'], 'values' => ['' => 'Выберите'] + \Money\Currency::getList()]);
}
$form->input('text', 'config[orderPrefix]', 'Префикс для номеров заказов', ['value' => App::$cur->ecommerce->config['orderPrefix']]);
$form->input('text', 'config[notify_mail]', 'E-mail оповещений о новых заказах', ['value' => App::$cur->ecommerce->config['notify_mail']]);
$form->input('hidden', 'config[save]', '', ['value' => 1]);
$form->end('Сохранить');
?>
    <h3>Обслужвание</h3>
    <a href="/admin/ecommerce/reSearchIndex" class="btn btn-primary">Обновить поисковые индексы</a>
    <h3>Уведомления в браузере</h3>
    <a id ="push-notifications-button" href="#" class="btn btn-primary">Получать уведомления</a>
    <script>
        inji.onLoad(function () {
          document.querySelector('#push-notifications-button').addEventListener('click', function () {
            if (!Notification) {
              alert('Desktop notifications not available in your browser. Try Chromium.');
示例#28
0
 /**
  * Returns the name as string of the given currency
  *
  * @param Currency $currency
  * @return string
  */
 public function formatCurrencyAsName(Currency $currency)
 {
     return $currency->getName();
 }
 /**
  * @param          $units
  * @param Currency $referenceCurrency
  * @param Currency $currency
  * @return string The endpoint to get Currency conversion
  */
 protected function getEndpoint($units, Currency $referenceCurrency, Currency $currency)
 {
     return sprintf('https://www.google.com/finance/converter?a=%s&from=%s&to=%s', $units, $referenceCurrency->getName(), $currency->getName());
 }
 /**
  * Creates an exception from Currency objects.
  *
  * @param Currency $baseCurrency
  * @param Currency $counterCurrency
  *
  * @return UnresolvableCurrencyPairException
  */
 public static function createFromCurrencies(Currency $baseCurrency, Currency $counterCurrency)
 {
     $message = sprintf('Cannot resolve a currency pair for currencies: %s/%s', $baseCurrency->getCode(), $counterCurrency->getCode());
     return new self($message);
 }