Skip to content

Instantly share code, notes, and snippets.

@ylastapis
Created July 29, 2016 12:49
Show Gist options
  • Save ylastapis/a4c1f2dab80febf17f24ffb560a952ef to your computer and use it in GitHub Desktop.
Save ylastapis/a4c1f2dab80febf17f24ffb560a952ef to your computer and use it in GitHub Desktop.
Locale Subscriber to force Locale over API calls on Sylius
<?php
namespace AppBundle\EventSubscriber;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Core\Locale\LocaleStorageInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Locale\Provider\LocaleProvider;
use Sylius\Component\Locale\Provider\LocaleProviderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleSubscriber implements EventSubscriberInterface
{
/**
* @var LocaleContextInterface
*/
protected $localeContext;
/**
* @var LocaleProvider
*/
private $localeProvider;
/**
* @var LocaleStorageInterface
*/
private $localeStorage;
/**
* @var ChannelContextInterface
*/
private $channelContext;
/**
* @param LocaleContextInterface $localeContext
* @param LocaleProviderInterface $localeProvider
* @param LocaleStorageInterface $localeStorage
* @param ChannelContextInterface $channelContext
*/
public function __construct(LocaleContextInterface $localeContext, LocaleProviderInterface $localeProvider, LocaleStorageInterface $localeStorage, ChannelContextInterface $channelContext)
{
$this->localeContext = $localeContext;
$this->localeProvider = $localeProvider;
$this->localeStorage = $localeStorage;
$this->channelContext = $channelContext;
}
/**
* Set the right locale via context.
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
if ($locale = $request->attributes->get('_locale')) {
$definedLocale = $this->localeContext->getLocaleCode() ? $this->localeContext->getLocaleCode() : $this->localeProvider->getDefaultLocaleCode();
// check validity of locale
if ($definedLocale !== $locale) {
if (in_array($locale, $this->localeProvider->getAvailableLocalesCodes())) {
$request->setLocale($locale);
$this->localeStorage->set($this->channelContext->getChannel(), $locale);
}
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 15]], // important, below than 16, after LocaleListener
];
}
}
services:
app.subscriber.locale:
class: AppBundle\EventSubscriber\LocaleSubscriber
arguments: [ "@sylius.context.locale", "@sylius.locale_provider", "@sylius.storage.locale", "@sylius.context.channel" ]
tags:
- { name: kernel.event_subscriber }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment