Skip to content

Commit 3c4d54f

Browse files
committed
MCP-288: [Load Cart Section] Replace Zend_Currency component with Intl NumberFormatter
- Add caching to number formatter currency object create;
1 parent cedb4c3 commit 3c4d54f

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

app/code/Magento/Directory/Model/Currency.php

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,11 @@ class Currency extends \Magento\Framework\Model\AbstractModel
8989
*/
9090
private $numberFormatter;
9191

92+
/**
93+
* @var array
94+
*/
95+
private $numberFormatterCache;
96+
9297
/**
9398
* @param \Magento\Framework\Model\Context $context
9499
* @param \Magento\Framework\Registry $registry
@@ -403,23 +408,39 @@ private function formatCurrency(string $price, array $options): string
403408
);
404409
$options += $customerOptions->toArray();
405410

406-
$this->numberFormatter = $this->numberFormatterFactory->create(
407-
['locale' => $this->localeResolver->getLocale(), 'style' => \NumberFormatter::CURRENCY]
408-
);
409-
410-
$this->setOptions($options);
411+
$this->numberFormatter = $this->getNumberFormatter($options);
411412

412413
$formattedCurrency = $this->numberFormatter->formatCurrency(
413414
$price, $this->getCode() ?? $this->numberFormatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE)
414415
);
415416

416-
if ((array_key_exists(LocaleCurrency::CURRENCY_OPTION_DISPLAY, $options)
417-
&& $options[LocaleCurrency::CURRENCY_OPTION_DISPLAY] === \Magento\Framework\Currency::NO_SYMBOL)
418-
|| array_key_exists(LocaleCurrency::CURRENCY_OPTION_SYMBOL, $options)) {
419-
$formattedCurrency = str_replace(' ', '', $formattedCurrency);
417+
if (array_key_exists(LocaleCurrency::CURRENCY_OPTION_SYMBOL, $options)) {
418+
// remove only one non-breaking space from custom currency symbol to allow custom NBSP in currency symbol
419+
$formattedCurrency = preg_replace('/ /u', '', $formattedCurrency, 1);
420+
}
421+
422+
return preg_replace('/^\s+|\s+$/u', '', $formattedCurrency);
423+
}
424+
425+
/**
426+
* Get NumberFormatter object from cache.
427+
*
428+
* @param array $options
429+
* @return \Magento\Framework\NumberFormatter
430+
*/
431+
private function getNumberFormatter(array $options): \Magento\Framework\NumberFormatter
432+
{
433+
$key = 'currency_' . md5($this->localeResolver->getLocale() . serialize($options));
434+
if (!isset($this->numberFormatterCache[$key])) {
435+
$this->numberFormatter = $this->numberFormatterFactory->create(
436+
['locale' => $this->localeResolver->getLocale(), 'style' => \NumberFormatter::CURRENCY]
437+
);
438+
439+
$this->setOptions($options);
440+
$this->numberFormatterCache[$key] = $this->numberFormatter;
420441
}
421442

422-
return $formattedCurrency;
443+
return $this->numberFormatterCache[$key];
423444
}
424445

425446
/**

0 commit comments

Comments
 (0)