<?php
namespace GlobusSW6\Subscriber;
use GlobusSW6\Service\CheckoutVisibility\CheckoutVisibilityManager;
use Psr\Log\LoggerInterface;
use Shopware\Core\Content\Product\ProductCollection;
use Shopware\Core\Framework\Adapter\Translation\Translator;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Shopware\Core\Framework\Api\Context\SystemSource;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CheckoutVisibilitiesSubscriber implements EventSubscriberInterface
{
/** @var CheckoutVisibilityManager */
private $checkoutVisibilityManager;
/** @var Translator */
private $translator;
/** @var LoggerInterface */
private $logger;
/**
* @param CheckoutVisibilityManager $checkoutVisibilityManager
* @param Translator $translator
* @param LoggerInterface $logger
*/
public function __construct(CheckoutVisibilityManager $checkoutVisibilityManager, Translator $translator, LoggerInterface $logger)
{
$this->checkoutVisibilityManager = $checkoutVisibilityManager;
$this->translator = $translator;
$this->logger = $logger;
}
public static function getSubscribedEvents():array
{
return [
'product.search.result.loaded' => 'onProductLoaded'
];
}
public function onProductLoaded(EntitySearchResultLoadedEvent $event)
{
if ($event->getContext()->getSource() instanceof SystemSource) {
return;
}
try {
$this->translator->injectSettings(
$event->getContext()->getSource()->getSalesChannelId(),
$event->getContext()->getLanguageId(),
'de-DE', // TODO-NGS: currently hardcoded
$event->getContext()
);
} catch (\Throwable $t) {
$this->logger->info('Unable to translate snippets for api calls using the following params: saleschannelId: ' . json_encode($event->getContext()->getSource()) . ' ; languageId: ' . $event->getContext()->getLanguageId() . ' ; context: ' . json_encode($event->getContext()) );
}
/** @var ProductCollection $products */
$products = $event->getResult()->getEntities();
if ($products === null) {
return;
}
if ( $event->getContext()->getSource() instanceOf SalesChannelApiSource){
$salesChannelId = $event->getContext()->getSource()->getSalesChannelId();
$this->checkoutVisibilityManager->handleVisibilities($products, $salesChannelId, $this->translator, $event->getContext()->getLanguageId());
}
}
}