vendor/sylius/sylius/src/Sylius/Component/Core/Currency/Context/ChannelAwareCurrencyContext.php line 22

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace Sylius\Component\Core\Currency\Context;
  12. use Sylius\Component\Channel\Context\ChannelContextInterface;
  13. use Sylius\Component\Core\Model\ChannelInterface;
  14. use Sylius\Component\Currency\Context\CurrencyContextInterface;
  15. use Sylius\Component\Currency\Context\CurrencyNotFoundException;
  16. use Sylius\Component\Currency\Model\CurrencyInterface;
  17. final class ChannelAwareCurrencyContext implements CurrencyContextInterface
  18. {
  19.     public function __construct(private CurrencyContextInterface $currencyContext, private ChannelContextInterface $channelContext)
  20.     {
  21.     }
  22.     public function getCurrencyCode(): string
  23.     {
  24.         /** @var ChannelInterface $channel */
  25.         $channel $this->channelContext->getChannel();
  26.         try {
  27.             $currencyCode $this->currencyContext->getCurrencyCode();
  28.             if (!$this->isAvailableCurrency($currencyCode$channel)) {
  29.                 return $channel->getBaseCurrency()->getCode();
  30.             }
  31.             return $currencyCode;
  32.         } catch (CurrencyNotFoundException) {
  33.             return $channel->getBaseCurrency()->getCode();
  34.         }
  35.     }
  36.     private function isAvailableCurrency(string $currencyCodeChannelInterface $channel): bool
  37.     {
  38.         $availableCurrencies array_map(
  39.             function (CurrencyInterface $currency) {
  40.                 return $currency->getCode();
  41.             },
  42.             $channel->getCurrencies()->toArray()
  43.         );
  44.         return in_array($currencyCode$availableCurrenciestrue);
  45.     }
  46. }