FixerIo.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Directory\Model\Currency\Import;
  7. use Magento\Store\Model\ScopeInterface;
  8. /**
  9. * Currency rate import model (From http://fixer.io/)
  10. */
  11. class FixerIo extends AbstractImport
  12. {
  13. /**
  14. * @var string
  15. */
  16. const CURRENCY_CONVERTER_URL = 'http://data.fixer.io/api/latest?access_key={{ACCESS_KEY}}'
  17. . '&base={{CURRENCY_FROM}}&symbols={{CURRENCY_TO}}';
  18. /**
  19. * Http Client Factory
  20. *
  21. * @var \Magento\Framework\HTTP\ZendClientFactory
  22. */
  23. protected $httpClientFactory;
  24. /**
  25. * Core scope config
  26. *
  27. * @var \Magento\Framework\App\Config\ScopeConfigInterface
  28. */
  29. private $scopeConfig;
  30. /**
  31. * Initialize dependencies
  32. *
  33. * @param \Magento\Directory\Model\CurrencyFactory $currencyFactory
  34. * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  35. * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
  36. */
  37. public function __construct(
  38. \Magento\Directory\Model\CurrencyFactory $currencyFactory,
  39. \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
  40. \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
  41. ) {
  42. parent::__construct($currencyFactory);
  43. $this->scopeConfig = $scopeConfig;
  44. $this->httpClientFactory = $httpClientFactory;
  45. }
  46. /**
  47. * @inheritdoc
  48. */
  49. public function fetchRates()
  50. {
  51. $data = [];
  52. $currencies = $this->_getCurrencyCodes();
  53. $defaultCurrencies = $this->_getDefaultCurrencyCodes();
  54. foreach ($defaultCurrencies as $currencyFrom) {
  55. if (!isset($data[$currencyFrom])) {
  56. $data[$currencyFrom] = [];
  57. }
  58. $data = $this->convertBatch($data, $currencyFrom, $currencies);
  59. ksort($data[$currencyFrom]);
  60. }
  61. return $data;
  62. }
  63. /**
  64. * @inheritdoc
  65. */
  66. protected function _convert($currencyFrom, $currencyTo)
  67. {
  68. }
  69. /**
  70. * Return currencies convert rates in batch mode
  71. *
  72. * @param array $data
  73. * @param string $currencyFrom
  74. * @param array $currenciesTo
  75. * @return array
  76. */
  77. private function convertBatch(array $data, string $currencyFrom, array $currenciesTo): array
  78. {
  79. $accessKey = $this->scopeConfig->getValue('currency/fixerio/api_key', ScopeInterface::SCOPE_STORE);
  80. if (empty($accessKey)) {
  81. $this->_messages[] = __('No API Key was specified or an invalid API Key was specified.');
  82. $data[$currencyFrom] = $this->makeEmptyResponse($currenciesTo);
  83. return $data;
  84. }
  85. $currenciesStr = implode(',', $currenciesTo);
  86. $url = str_replace(
  87. ['{{ACCESS_KEY}}', '{{CURRENCY_FROM}}', '{{CURRENCY_TO}}'],
  88. [$accessKey, $currencyFrom, $currenciesStr],
  89. self::CURRENCY_CONVERTER_URL
  90. );
  91. set_time_limit(0);
  92. try {
  93. $response = $this->getServiceResponse($url);
  94. } finally {
  95. ini_restore('max_execution_time');
  96. }
  97. if (!$this->validateResponse($response, $currencyFrom)) {
  98. $data[$currencyFrom] = $this->makeEmptyResponse($currenciesTo);
  99. return $data;
  100. }
  101. foreach ($currenciesTo as $currencyTo) {
  102. if ($currencyFrom == $currencyTo) {
  103. $data[$currencyFrom][$currencyTo] = $this->_numberFormat(1);
  104. } else {
  105. if (empty($response['rates'][$currencyTo])) {
  106. $this->_messages[] = __('We can\'t retrieve a rate from %1 for %2.', $url, $currencyTo);
  107. $data[$currencyFrom][$currencyTo] = null;
  108. } else {
  109. $data[$currencyFrom][$currencyTo] = $this->_numberFormat(
  110. (double)$response['rates'][$currencyTo]
  111. );
  112. }
  113. }
  114. }
  115. return $data;
  116. }
  117. /**
  118. * Get Fixer.io service response
  119. *
  120. * @param string $url
  121. * @param int $retry
  122. * @return array
  123. */
  124. private function getServiceResponse(string $url, int $retry = 0): array
  125. {
  126. /** @var \Magento\Framework\HTTP\ZendClient $httpClient */
  127. $httpClient = $this->httpClientFactory->create();
  128. $response = [];
  129. try {
  130. $jsonResponse = $httpClient->setUri($url)
  131. ->setConfig(
  132. [
  133. 'timeout' => $this->scopeConfig->getValue(
  134. 'currency/fixerio/timeout',
  135. ScopeInterface::SCOPE_STORE
  136. ),
  137. ]
  138. )
  139. ->request('GET')
  140. ->getBody();
  141. $response = json_decode($jsonResponse, true);
  142. } catch (\Exception $e) {
  143. if ($retry == 0) {
  144. $response = $this->getServiceResponse($url, 1);
  145. }
  146. }
  147. return $response;
  148. }
  149. /**
  150. * Validates rates response.
  151. *
  152. * @param array $response
  153. * @param string $baseCurrency
  154. * @return bool
  155. */
  156. private function validateResponse(array $response, string $baseCurrency): bool
  157. {
  158. if ($response['success']) {
  159. return true;
  160. }
  161. $errorCodes = [
  162. 101 => __('No API Key was specified or an invalid API Key was specified.'),
  163. 102 => __('The account this API request is coming from is inactive.'),
  164. 105 => __('The "%1" is not allowed as base currency for your subscription plan.', $baseCurrency),
  165. 201 => __('An invalid base currency has been entered.'),
  166. ];
  167. $this->_messages[] = $errorCodes[$response['error']['code']] ?? __('Currency rates can\'t be retrieved.');
  168. return false;
  169. }
  170. /**
  171. * Creates array for provided currencies with empty rates.
  172. *
  173. * @param array $currenciesTo
  174. * @return array
  175. */
  176. private function makeEmptyResponse(array $currenciesTo): array
  177. {
  178. return array_fill_keys($currenciesTo, null);
  179. }
  180. }