Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Currency.php
Go to the documentation of this file.
1 <?php
10 namespace Magento\Directory\Block;
11 
13 
19 {
23  protected $_currencyFactory;
24 
28  protected $_postDataHelper;
29 
33  protected $localeResolver;
34 
42  public function __construct(
43  \Magento\Framework\View\Element\Template\Context $context,
44  \Magento\Directory\Model\CurrencyFactory $currencyFactory,
45  \Magento\Framework\Data\Helper\PostHelper $postDataHelper,
46  \Magento\Framework\Locale\ResolverInterface $localeResolver,
47  array $data = []
48  ) {
49  $this->_currencyFactory = $currencyFactory;
50  $this->_postDataHelper = $postDataHelper;
51  parent::__construct($context, $data);
52  $this->localeResolver = $localeResolver;
53  }
54 
61  public function getCurrencyCount()
62  {
63  return count($this->getCurrencies());
64  }
65 
73  public function getCurrencies()
74  {
75  $currencies = $this->getData('currencies');
76  if ($currencies === null) {
77  $currencies = [];
78  $codes = $this->_storeManager->getStore()->getAvailableCurrencyCodes(true);
79  if (is_array($codes) && count($codes) > 1) {
80  $rates = $this->_currencyFactory->create()->getCurrencyRates(
81  $this->_storeManager->getStore()->getBaseCurrency(),
82  $codes
83  );
84 
85  foreach ($codes as $code) {
86  if (isset($rates[$code])) {
87  $allCurrencies = (new CurrencyBundle())->get(
88  $this->localeResolver->getLocale()
89  )['Currencies'];
90  $currencies[$code] = $allCurrencies[$code][1] ?: $code;
91  }
92  }
93  }
94 
95  $this->setData('currencies', $currencies);
96  }
97  return $currencies;
98  }
99 
105  public function getSwitchUrl()
106  {
107  return $this->getUrl('directory/currency/switch');
108  }
109 
117  {
118  return $this->_postDataHelper->getPostData($this->escapeUrl($this->getSwitchUrl()), ['currency' => $code]);
119  }
120 
126  public function getCurrentCurrencyCode()
127  {
128  if ($this->_getData('current_currency_code') === null) {
129  // do not use $this->_storeManager->getStore()->getCurrentCurrencyCode() because of probability
130  // to get an invalid (without base rate) currency from code saved in session
131  $this->setData('current_currency_code', $this->_storeManager->getStore()->getCurrentCurrency()->getCode());
132  }
133  return $this->_getData('current_currency_code');
134  }
135 
139  public function getStoreCode()
140  {
141  return $this->_storeManager->getStore()->getCode();
142  }
143 }
getData($key='', $index=null)
Definition: DataObject.php:119
$rates
Definition: tax.phtml:35
__construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Framework\Data\Helper\PostHelper $postDataHelper, \Magento\Framework\Locale\ResolverInterface $localeResolver, array $data=[])
Definition: Currency.php:42
setData($key, $value=null)
Definition: DataObject.php:72
$code
Definition: info.phtml:12