vendor/ibexa/product-catalog/src/lib/Money/IntlMoneyFactory.php line 47

Open in your IDE?
  1. <?php
  2. /**
  3. * @copyright Copyright (C) Ibexa AS. All rights reserved.
  4. * @license For full copyright and license information view LICENSE file distributed with this source code.
  5. */
  6. declare(strict_types=1);
  7. namespace Ibexa\ProductCatalog\Money;
  8. use Ibexa\Contracts\Core\Repository\Iterator\BatchIterator;
  9. use Ibexa\Contracts\ProductCatalog\CurrencyServiceInterface;
  10. use Ibexa\Contracts\ProductCatalog\Iterator\BatchIteratorAdapter\CurrencyFetchAdapter;
  11. use Ibexa\Core\MVC\Symfony\MVCEvents;
  12. use Ibexa\ProductCatalog\NumberFormatter\NumberFormatterFactoryInterface;
  13. use Money\Currencies\CurrencyList;
  14. use Money\Formatter\IntlMoneyFormatter;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. class IntlMoneyFactory implements EventSubscriberInterface
  17. {
  18. private const CURRENCIES_LOAD_BATCH_SIZE = 200;
  19. private CurrencyServiceInterface $currencyService;
  20. private NumberFormatterFactoryInterface $numberFormatterFactory;
  21. private ?CurrencyList $currencies;
  22. private ?IntlMoneyFormatter $moneyFormatter;
  23. public function __construct(
  24. CurrencyServiceInterface $currencyService,
  25. NumberFormatterFactoryInterface $numberFormatterFactory
  26. ) {
  27. $this->currencyService = $currencyService;
  28. $this->numberFormatterFactory = $numberFormatterFactory;
  29. }
  30. public static function getSubscribedEvents(): array
  31. {
  32. return [
  33. MVCEvents::CONFIG_SCOPE_CHANGE => 'reset',
  34. ];
  35. }
  36. public function reset(): void
  37. {
  38. $this->moneyFormatter = null;
  39. $this->currencies = null;
  40. }
  41. public function getMoneyFormatter(): IntlMoneyFormatter
  42. {
  43. if (!isset($this->moneyFormatter)) {
  44. $currencies = $this->loadCurrencies();
  45. $this->moneyFormatter = new IntlMoneyFormatter(
  46. $this->numberFormatterFactory->createNumberFormatter(),
  47. $currencies
  48. );
  49. }
  50. return $this->moneyFormatter;
  51. }
  52. private function loadCurrencies(): CurrencyList
  53. {
  54. if (!isset($this->currencies)) {
  55. $currencyCodeToSubunitsMap = [];
  56. /** @var iterable<\Ibexa\Contracts\ProductCatalog\Values\CurrencyInterface> $currencies */
  57. $currencies = new BatchIterator(
  58. new CurrencyFetchAdapter($this->currencyService),
  59. self::CURRENCIES_LOAD_BATCH_SIZE
  60. );
  61. foreach ($currencies as $currency) {
  62. $currencyCodeToSubunitsMap[$currency->getCode()] = $currency->getSubUnits();
  63. }
  64. $this->currencies = new CurrencyList($currencyCodeToSubunitsMap);
  65. }
  66. return $this->currencies;
  67. }
  68. }