Completed
Push — layout-caching ( bff40d...dc5564 )
by Kamil
67:32 queued 46:25
created

ChannelAwareCurrencyContext::isAvailableCurrency()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
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\Core\Currency\Context;
13
14
use Sylius\Component\Channel\Context\ChannelContextInterface;
15
use Sylius\Component\Core\Model\ChannelInterface;
16
use Sylius\Component\Currency\Context\CurrencyContextInterface;
17
use Sylius\Component\Currency\Context\CurrencyNotFoundException;
18
use Sylius\Component\Currency\Model\CurrencyInterface;
19
20
/**
21
 * @author Kamil Kokot <[email protected]>
22
 */
23
final class ChannelAwareCurrencyContext implements CurrencyContextInterface
24
{
25
    /**
26
     * @var CurrencyContextInterface
27
     */
28
    private $currencyContext;
29
30
    /**
31
     * @var ChannelContextInterface
32
     */
33
    private $channelContext;
34
35
    /**
36
     * @param CurrencyContextInterface $currencyContext
37
     * @param ChannelContextInterface $channelContext
38
     */
39
    public function __construct(CurrencyContextInterface $currencyContext, ChannelContextInterface$channelContext)
40
    {
41
        $this->currencyContext = $currencyContext;
42
        $this->channelContext = $channelContext;
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function getCurrencyCode()
49
    {
50
        /** @var ChannelInterface $channel */
51
        $channel = $this->channelContext->getChannel();
52
53
        try {
54
            $currencyCode = $this->currencyContext->getCurrencyCode();
55
56
            if (!$this->isAvailableCurrency($currencyCode, $channel)) {
57
                return $channel->getBaseCurrency()->getCode();
58
            }
59
60
            return $currencyCode;
61
        } catch (CurrencyNotFoundException $exception) {
62
            return $channel->getBaseCurrency()->getCode();
63
        }
64
    }
65
66
    /**
67
     * @param string $currencyCode
68
     * @param ChannelInterface $channel
69
     *
70
     * @return bool
71
     */
72
    private function isAvailableCurrency($currencyCode, ChannelInterface $channel)
73
    {
74
        $availableCurrencies = array_map(
75
            function (CurrencyInterface $currency) {
76
                return $currency->getCode();
77
            },
78
            $channel->getCurrencies()->toArray()
79
        );
80
81
        return in_array($currencyCode, $availableCurrencies, true);
82
    }
83
}
84