-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
Currency.php
531 lines (478 loc) · 15.3 KB
/
Currency.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Directory\Model;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\InputException;
use Magento\Directory\Model\Currency\Filter;
use Magento\Framework\Locale\Currency as LocaleCurrency;
use Magento\Framework\Locale\ResolverInterface as LocalResolverInterface;
/**
* Currency model
*
* @api
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @since 100.0.2
*/
class Currency extends \Magento\Framework\Model\AbstractModel
{
/**
* CONFIG path constants
*/
const XML_PATH_CURRENCY_ALLOW = 'currency/options/allow';
const XML_PATH_CURRENCY_DEFAULT = 'currency/options/default';
const XML_PATH_CURRENCY_BASE = 'currency/options/base';
/**
* @var Filter
*/
protected $_filter;
/**
* Currency Rates
*
* @var array
*/
protected $_rates;
/**
* @var \Magento\Framework\Locale\FormatInterface
*/
protected $_localeFormat;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @var \Magento\Directory\Helper\Data
*/
protected $_directoryHelper;
/**
* @var \Magento\Directory\Model\Currency\FilterFactory
*/
protected $_currencyFilterFactory;
/**
* @var \Magento\Framework\Locale\CurrencyInterface
*/
protected $_localeCurrency;
/**
* @var CurrencyConfig
*/
private $currencyConfig;
/**
* @var LocalResolverInterface
*/
private $localeResolver;
/**
* @var \Magento\Framework\NumberFormatterFactory
*/
private $numberFormatterFactory;
/**
* @var \Magento\Framework\NumberFormatter
*/
private $numberFormatter;
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Locale\FormatInterface $localeFormat
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Directory\Helper\Data $directoryHelper
* @param Currency\FilterFactory $currencyFilterFactory
* @param \Magento\Framework\Locale\CurrencyInterface $localeCurrency
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data
* @param CurrencyConfig|null $currencyConfig
* @param LocalResolverInterface|null $localeResolver
* @param \Magento\Framework\NumberFormatterFactory|null $numberFormatterFactory
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Locale\FormatInterface $localeFormat,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Directory\Helper\Data $directoryHelper,
\Magento\Directory\Model\Currency\FilterFactory $currencyFilterFactory,
\Magento\Framework\Locale\CurrencyInterface $localeCurrency,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = [],
CurrencyConfig $currencyConfig = null,
LocalResolverInterface $localeResolver = null,
\Magento\Framework\NumberFormatter $numberFormatterFactory = null
) {
parent::__construct(
$context,
$registry,
$resource,
$resourceCollection,
$data
);
$this->_localeFormat = $localeFormat;
$this->_storeManager = $storeManager;
$this->_directoryHelper = $directoryHelper;
$this->_currencyFilterFactory = $currencyFilterFactory;
$this->_localeCurrency = $localeCurrency;
$this->currencyConfig = $currencyConfig ?: ObjectManager::getInstance()->get(CurrencyConfig::class);
$this->localeResolver = $localeResolver ?: ObjectManager::getInstance()->get(LocalResolverInterface::class);
$this->numberFormatterFactory = $numberFormatterFactory ?: ObjectManager::getInstance()->get(\Magento\Framework\NumberFormatterFactory::class);
}
/**
* @return void
*/
protected function _construct()
{
$this->_init(\Magento\Directory\Model\ResourceModel\Currency::class);
}
/**
* Get currency code
*
* @return string
*/
public function getCode()
{
return $this->_getData('currency_code');
}
/**
* Get currency code
*
* @return string
*/
public function getCurrencyCode()
{
return $this->_getData('currency_code');
}
/**
* Currency Rates getter
*
* @return array
*/
public function getRates()
{
return $this->_rates;
}
/**
* Currency Rates setter
*
* @param array $rates Currency Rates
* @return $this
*/
public function setRates(array $rates)
{
$this->_rates = $rates;
return $this;
}
/**
* Loading currency data
*
* @param string $id
* @param string $field
* @return $this
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function load($id, $field = null)
{
$this->unsRate();
$this->setData('currency_code', $id);
return $this;
}
/**
* Get currency rate (only base => allowed)
*
* @param mixed $toCurrency
* @return float
*/
public function getRate($toCurrency)
{
$code = $this->getCurrencyCodeFromToCurrency($toCurrency);
$rates = $this->getRates();
if (!isset($rates[$code])) {
$rates[$code] = $this->_getResource()->getRate($this->getCode(), $toCurrency);
$this->setRates($rates);
}
return $rates[$code];
}
/**
* Get currency rate (base=>allowed or allowed=>base)
*
* @param mixed $toCurrency
* @return float
*/
public function getAnyRate($toCurrency)
{
$code = $this->getCurrencyCodeFromToCurrency($toCurrency);
$rates = $this->getRates();
if (!isset($rates[$code])) {
$rates[$code] = $this->_getResource()->getAnyRate($this->getCode(), $toCurrency);
$this->setRates($rates);
}
return $rates[$code];
}
/**
* Convert price to currency format
*
* @param float $price
* @param mixed $toCurrency
* @return float
* @throws \Exception
*/
public function convert($price, $toCurrency = null)
{
if ($toCurrency === null) {
return $price;
} elseif ($rate = $this->getRate($toCurrency)) {
return (float)$price * (float)$rate;
}
throw new \Exception(__(
'Undefined rate from "%1-%2".',
$this->getCode(),
$this->getCurrencyCodeFromToCurrency($toCurrency)
));
}
/**
* @param mixed $toCurrency
* @return string
* @throws \Magento\Framework\Exception\InputException
*/
private function getCurrencyCodeFromToCurrency($toCurrency)
{
if (is_string($toCurrency)) {
$code = $toCurrency;
} elseif ($toCurrency instanceof \Magento\Directory\Model\Currency) {
$code = $toCurrency->getCurrencyCode();
} else {
throw new InputException(__('Please correct the target currency.'));
}
return $code;
}
/**
* Get currency filter
*
* @return Filter
*/
public function getFilter()
{
if (!$this->_filter) {
$this->_filter = $this->_currencyFilterFactory->create(['code' => $this->getCode()]);
}
return $this->_filter;
}
/**
* Format price to currency format
*
* @param float $price
* @param array $options
* @param bool $includeContainer
* @param bool $addBrackets
* @return string
*/
public function format($price, $options = [], $includeContainer = true, $addBrackets = false)
{
return $this->formatPrecision($price, 2, $options, $includeContainer, $addBrackets);
}
/**
* Apply currency format to number with specific rounding precision
*
* @param float $price
* @param int $precision
* @param array $options
* @param bool $includeContainer
* @param bool $addBrackets
* @return string
*/
public function formatPrecision(
$price,
$precision,
$options = [],
$includeContainer = true,
$addBrackets = false
) {
if (!isset($options['precision'])) {
$options['precision'] = $precision;
}
if ($includeContainer) {
return '<span class="price">' . ($addBrackets ? '[' : '') . $this->formatTxt(
$price,
$options
) . ($addBrackets ? ']' : '') . '</span>';
}
return $this->formatTxt($price, $options);
}
/**
* @param float $price
* @param array $options
* @return string
*/
public function formatTxt($price, $options = [])
{
if (!is_numeric($price)) {
$price = $this->_localeFormat->getNumber($price);
}
/**
* Fix problem with 12 000 000, 1 200 000
*
* %f - the argument is treated as a float, and presented as a floating-point number (locale aware).
* %F - the argument is treated as a float, and presented as a floating-point number (non-locale aware).
*/
$price = sprintf("%F", $price);
if ($this->useNumberFormatter($options)) {
return $this->formatCurrency($price, $options);
}
return $this->_localeCurrency->getCurrency($this->getCode())->toCurrency($price, $options);
}
/**
* Check if to use Intl.NumberFormatter to format currency.
*
* @param array $options
* @return bool
*/
private function useNumberFormatter(array $options): bool
{
return (empty($options) || array_key_exists(LocaleCurrency::CURRENCY_OPTION_SYMBOL, $options)
|| (array_key_exists(LocaleCurrency::CURRENCY_OPTION_DISPLAY, $options)
&& ($options[LocaleCurrency::CURRENCY_OPTION_DISPLAY] === \Magento\Framework\Currency::NO_SYMBOL
|| $options[LocaleCurrency::CURRENCY_OPTION_DISPLAY] === \Magento\Framework\Currency::USE_SYMBOL))
|| array_key_exists('precision', $options));
}
/**
* Format currency.
*
* @param string $price
* @param array $options
* @return string
*/
private function formatCurrency(string $price, array $options): string
{
$customerOptions = new \Magento\Framework\DataObject([]);
$this->_eventManager->dispatch(
'currency_display_options_forming',
['currency_options' => $customerOptions, 'base_code' => $this->getCode()]
);
$options = array_merge($options, $customerOptions->toArray());
$this->numberFormatter = $this->numberFormatterFactory->create(
['locale' => $this->localeResolver->getLocale(), 'style' => \NumberFormatter::CURRENCY]
);
$this->setOptions($options);
$formattedCurrency = $this->numberFormatter->formatCurrency($price, $this->getCode());
if (array_key_exists(LocaleCurrency::CURRENCY_OPTION_DISPLAY, $options)
&& $options[LocaleCurrency::CURRENCY_OPTION_DISPLAY] === \Magento\Framework\Currency::NO_SYMBOL) {
$formattedCurrency = str_replace(' ', '', $formattedCurrency);
}
return $formattedCurrency;
}
/**
* Set number formatter custom options.
*
* @param array $options
* @return void
*/
private function setOptions(array $options): void
{
if (array_key_exists(LocaleCurrency::CURRENCY_OPTION_DISPLAY, $options)
&& $options[LocaleCurrency::CURRENCY_OPTION_DISPLAY] === \Magento\Framework\Currency::NO_SYMBOL) {
$this->numberFormatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, '');
}
if (array_key_exists('precision', $options)) {
$this->numberFormatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $options['precision']);
}
if (array_key_exists(LocaleCurrency::CURRENCY_OPTION_SYMBOL, $options)) {
$this->numberFormatter->setSymbol(
\NumberFormatter::CURRENCY_SYMBOL, $options[LocaleCurrency::CURRENCY_OPTION_SYMBOL]
);
}
}
/**
* Return currency symbol for current locale and currency code
*
* @return string
*/
public function getCurrencySymbol()
{
return $this->_localeCurrency->getCurrency($this->getCode())->getSymbol();
}
/**
* @return string
*/
public function getOutputFormat()
{
$formatted = $this->formatTxt(0);
$number = $this->formatTxt(0, ['display' => \Magento\Framework\Currency::NO_SYMBOL]);
return str_replace($this->trimUnicodeDirectionMark($number), '%s', $formatted);
}
/**
* Retrieve allowed currencies according to config
*
* @return array
*/
public function getConfigAllowCurrencies()
{
$allowedCurrencies = $this->currencyConfig->getConfigCurrencies(self::XML_PATH_CURRENCY_ALLOW);
$appBaseCurrencyCode = $this->_directoryHelper->getBaseCurrencyCode();
if (!in_array($appBaseCurrencyCode, $allowedCurrencies)) {
$allowedCurrencies[] = $appBaseCurrencyCode;
}
foreach ($this->_storeManager->getStores() as $store) {
$code = $store->getBaseCurrencyCode();
if (!in_array($code, $allowedCurrencies)) {
$allowedCurrencies[] = $code;
}
}
return $allowedCurrencies;
}
/**
* Retrieve default currencies according to config
*
* @return array
*/
public function getConfigDefaultCurrencies()
{
return $this->currencyConfig->getConfigCurrencies(self::XML_PATH_CURRENCY_DEFAULT);
}
/**
* @return array
*/
public function getConfigBaseCurrencies()
{
return $this->currencyConfig->getConfigCurrencies(self::XML_PATH_CURRENCY_BASE);
}
/**
* Retrieve currency rates to other currencies
*
* @param string $currency
* @param array|null $toCurrencies
* @return array
*/
public function getCurrencyRates($currency, $toCurrencies = null)
{
if ($currency instanceof \Magento\Directory\Model\Currency) {
$currency = $currency->getCode();
}
$data = $this->_getResource()->getCurrencyRates($currency, $toCurrencies);
return $data;
}
/**
* Save currency rates
*
* @param array $rates
* @return $this
*/
public function saveRates($rates)
{
$this->_getResource()->saveRates($rates);
return $this;
}
/**
* This method removes LRM and RLM marks from string
*
* @param string $string
* @return $this
*/
private function trimUnicodeDirectionMark($string)
{
if (preg_match('/^(\x{200E}|\x{200F})/u', $string, $match)) {
$string = preg_replace('/^'.$match[1].'/u', '', $string);
}
return $string;
}
}