<?php
declare(strict_types=1);
namespace SchilderSysteme\Subscriber;
use Doctrine\DBAL\Connection;
use SchilderSysteme\Traits\ThemeTrait;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Storefront\Pagelet\Header\HeaderPageletLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class HeaderSubscriber implements EventSubscriberInterface
{
use ThemeTrait;
private $productRepository;
private $connection;
private $themeRepository;
public function __construct(
EntityRepositoryInterface $productRepository,
Connection $connection,
EntityRepositoryInterface $themeRepository
)
{
$this->productRepository = $productRepository;
$this->connection = $connection;
$this->themeRepository = $themeRepository;
}
public static function getSubscribedEvents(): array
{
return [
HeaderPageletLoadedEvent::class => 'onHeaderLoaded'
];
}
public function onHeaderLoaded(HeaderPageletLoadedEvent $event)
{
if(!$this->isCorrectTheme($event->getContext(), $event->getSalesChannelContext(), $this->themeRepository)){
return;
}
$topsellerIds = $this->getTopsellersIds();
$criteria = new Criteria($topsellerIds);
$products = $this->productRepository->search($criteria, $event->getContext());
$event->getPagelet()->addExtension('topsellerProducts', $products);
}
private function getTopsellersIds()
{
$queryBuilder = $this->connection->createQueryBuilder();
return $queryBuilder->select('referenced_id, label, sum(quantity) as sales')
->from('order_line_item', 'item')
->join('item', 'product', 'product', 'item.product_id = product.id')
->where('product.active = 1')
->groupBy('item.product_id')
->orderBy('sales', 'desc')
->setMaxResults(20)
->execute()->fetchFirstColumn();
}
}