<?php declare(strict_types=1);
namespace Ew\GrecoBundle\Subscriber;
use Ew\GrecoBundle\Service\BundleService;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
private BundleService $bundleService;
private EntityRepository $customerDnaProductRepository;
public function __construct(
BundleService $bundleService,
EntityRepository $customerDnaProductRepository
)
{
$this->bundleService = $bundleService;
$this->customerDnaProductRepository = $customerDnaProductRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductLoaded',
ProductEvents::PRODUCT_LISTING_RESULT => 'onProductListingLoaded'
];
}
public function onProductLoaded(ProductPageLoadedEvent $event): void
{
try {
$productId = $event->getPage()->getProduct()->getId();
$customer = $event->getSalesChannelContext()->getCustomer();
$customerId = null;
if ($customer) {
$customerId = $customer->getId();
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productId', $productId));
$criteria->addFilter(new EqualsFilter('customerId', $customerId));
$customerDnaProduct = $this->customerDnaProductRepository->search($criteria, $event->getContext())->getEntities();
if (count($customerDnaProduct) > 0) {
$event->getPage()->getProduct()->setExtensions([
'bought' => true,
]);
}
} catch (\Exception $exception) {
}
}
public function onProductListingLoaded(ProductListingResultEvent $event): void
{
$customer = $event->getSalesChannelContext()->getCustomer();
$customerId = null;
if ($customer) {
$customerId = $customer->getId();
}
foreach ($event->getResult()->getEntities()->getElements() as $entity) {
$productId = $entity->getId();
if ($productId && $customerId) {
$checkBoughtDnaProduct = $this->bundleService->ifCustomerBoughtProduct($productId, $customerId, $event->getContext());
if ($checkBoughtDnaProduct) {
$entity->getExtensions()['foreignKeys']->setExtensions(['bought' => true]);
$entity->setExtensions(
$entity->getExtensions()
);
}
}
}
}
}