src/WellCommerce/Bundle/AppBundle/EventListener/CurrencySubscriber.php line 39

Open in your IDE?
  1. <?php
  2. declare(strict_types=0);
  3. /*
  4.  * WellCommerce Foundation
  5.  *
  6.  * This file is part of the WellCommerce package.
  7.  *
  8.  * (c) Adam Piotrowski <adam@wellcommerce.org>, Adrian Potepa <adrian@wellcommerce.org>
  9.  *
  10.  * For the full copyright and license information,
  11.  * please view the LICENSE file that was distributed with this source code.
  12.  */
  13. namespace WellCommerce\Bundle\AppBundle\EventListener;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  17. use Symfony\Component\HttpKernel\KernelEvents;
  18. use WellCommerce\Bundle\AppBundle\Entity\Currency;
  19. use WellCommerce\Bundle\AppBundle\Entity\Locale;
  20. use WellCommerce\Bundle\CoreBundle\DependencyInjection\AbstractServiceSubscriber;
  21. /**
  22.  * Class CurrencySubscriber
  23.  *
  24.  * @author  Adam Piotrowski <adam@wellcommerce.org>
  25.  */
  26. class CurrencySubscriber extends AbstractServiceSubscriber implements EventSubscriberInterface
  27. {
  28.     public static function getSubscribedEvents()
  29.     {
  30.         return [
  31.             KernelEvents::CONTROLLER => ['onKernelController', -100],
  32.         ];
  33.     }
  34.     public function onKernelController(ControllerEvent $event)
  35.     {
  36.         $request  $event->getRequest();
  37.         $session  $request->getSession();
  38.         $currency $session->get('_currency''');
  39.         if (empty($currency)) {
  40.             $currency $this->getLocaleCurrency($request);
  41.             if (!empty($currency)) {
  42.                 $session->set('_currency'$currency);
  43.             } else {
  44.                 $session->set('_currency''PLN');
  45.             }
  46.         }
  47.     }
  48.     protected function getLocaleCurrency(Request $request)
  49.     {
  50.         $currentLocale $request->getLocale();
  51.         $repository    $this->getEntityManager()->getRepository(Locale::class);
  52.         $locale        $repository->findOneBy(['code' => $currentLocale]);
  53.         if ($locale instanceof Locale && $locale->getCurrency() instanceof Currency) {
  54.             return $locale->getCurrency()->getCode();
  55.         }
  56.         return $repository->findOneBy([])->getCurrency()->getCode();
  57.     }
  58. }