<?php
declare(strict_types=0);
/*
* WellCommerce Foundation
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>, Adrian Potepa <adrian@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use WellCommerce\Bundle\AppBundle\Entity\Currency;
use WellCommerce\Bundle\AppBundle\Entity\Locale;
use WellCommerce\Bundle\CoreBundle\DependencyInjection\AbstractServiceSubscriber;
/**
* Class CurrencySubscriber
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class CurrencySubscriber extends AbstractServiceSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => ['onKernelController', -100],
];
}
public function onKernelController(ControllerEvent $event)
{
$request = $event->getRequest();
$session = $request->getSession();
$currency = $session->get('_currency', '');
if (empty($currency)) {
$currency = $this->getLocaleCurrency($request);
if (!empty($currency)) {
$session->set('_currency', $currency);
} else {
$session->set('_currency', 'PLN');
}
}
}
protected function getLocaleCurrency(Request $request)
{
$currentLocale = $request->getLocale();
$repository = $this->getEntityManager()->getRepository(Locale::class);
$locale = $repository->findOneBy(['code' => $currentLocale]);
if ($locale instanceof Locale && $locale->getCurrency() instanceof Currency) {
return $locale->getCurrency()->getCode();
}
return $repository->findOneBy([])->getCurrency()->getCode();
}
}