Completed
Push — master ( 55daec...2d65d3 )
by Kamil
18:26
created

CurrencyConverter::convert()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.4285
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Component\Currency\Converter;
13
14
use Sylius\Component\Currency\Model\CurrencyInterface;
15
use Sylius\Component\Resource\Repository\RepositoryInterface;
16
17
/**
18
 * @author Paweł Jędrzejewski <[email protected]>
19
 */
20
class CurrencyConverter implements CurrencyConverterInterface
21
{
22
    /**
23
     * @var RepositoryInterface
24
     */
25
    protected $currencyRepository;
26
27
    /**
28
     * @var array
29
     */
30
    private $cache;
31
32
    /**
33
     * @param RepositoryInterface $currencyRepository
34
     */
35
    public function __construct(RepositoryInterface $currencyRepository)
36
    {
37
        $this->currencyRepository = $currencyRepository;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function convertFromBase($amount, $targetCurrencyCode)
44
    {
45
        $currency = $this->getCurrency($targetCurrencyCode);
46
47
        if (null === $currency) {
48
            throw new UnavailableCurrencyException($targetCurrencyCode);
49
        }
50
51
        return (int) round($amount * $currency->getExchangeRate());
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function convertToBase($amount, $sourceCurrencyCode)
58
    {
59
        $currency = $this->getCurrency($sourceCurrencyCode);
60
61
        if (null === $currency) {
62
            throw new UnavailableCurrencyException($sourceCurrencyCode);
63
        }
64
65
        return (int) round($amount / $currency->getExchangeRate());
66
    }
67
68
    /**
69
     * @param string $code
70
     *
71
     * @return CurrencyInterface
72
     */
73
    private function getCurrency($code)
74
    {
75
        if (isset($this->cache[$code])) {
76
            return $this->cache[$code];
77
        }
78
79
        return $this->cache[$code] = $this->currencyRepository->findOneBy(['code' => $code]);
80
    }
81
}
82