/
CurrencyFormatter.php
69 lines (57 loc) · 2.25 KB
/
CurrencyFormatter.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
<?php declare(strict_types=1);
namespace Shopware\Core\System\Currency;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Language\LanguageEntity;
use Shopware\Core\Framework\Routing\Exception\LanguageNotFoundException;
class CurrencyFormatter
{
/**
* @var EntityRepositoryInterface
*/
protected $languageRepository;
/**
* @var array
*/
protected $localeCache = [];
public function __construct(EntityRepositoryInterface $languageRepository)
{
$this->languageRepository = $languageRepository;
}
/**
* @throws InconsistentCriteriaIdsException
* @throws LanguageNotFoundException
*/
public function formatCurrencyByLanguage(float $price, string $currency, string $languageId, Context $context): string
{
if (!array_key_exists($languageId, $this->localeCache)) {
$criteria = (new Criteria())
->addAssociation('locale')
->addFilter(new EqualsFilter('language.id', $languageId));
/** @var LanguageEntity|null $language */
$language = $this->languageRepository->search($criteria, $context)->get($languageId);
if ($language === null) {
throw new LanguageNotFoundException($languageId);
}
$this->localeCache[$languageId] = $language->getLocale()->getCode();
}
return $this->formatCurrency($price, $this->localeCache[$languageId], $currency);
}
public function formatCurrency(
float $price,
string $locale,
string $currency,
int $format = \NumberFormatter::CURRENCY,
?string $pattern = null
): ?string {
if ($pattern === null) {
$numberFormatter = new \NumberFormatter($locale, $format);
} else {
$numberFormatter = new \NumberFormatter($locale, $format, $pattern);
}
return $numberFormatter->formatCurrency($price, $currency);
}
}