<?php
declare(strict_types=1);
namespace Ks\Attachments\Subscriber;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Ks\Attachments\Service\AttachmentService;
/**
* Class PageSubscriber
* @package Ks\Attachments\Subscriber
*/
class PageSubscriber implements EventSubscriberInterface
{
const ENABLE_STATUS = 1;
private $attachmentsRepository;
private $attachmentService;
/**
* PageSubscriber constructor.
* @param EntityRepositoryInterface $attachmentsRepository
* @param AttachmentService $attachmentService
*/
public function __construct(
EntityRepositoryInterface $attachmentsRepository,
AttachmentService $attachmentService
) {
$this->attachmentsRepository = $attachmentsRepository;
$this->attachmentService = $attachmentService;
}
/**
* @return array|array[]
*/
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => ['onProductPageLoaded', 100],
ProductListingResultEvent::class => 'onProductListingResult'
];
}
/**
* @param ProductPageLoadedEvent $event
*/
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
$attachments = $this->attachmentService->getAttachmentForLoadedPage($event);
if ($attachments->getTotal() > 0) {
$attachments = $attachments->getElements();
$event->getPage()->getProduct()->assign(
[
'KsAttachments' => [
'attachments' => $attachments
]
]
);
} else {
return;
}
}
/**
* @param ProductListingResultEvent $event
*/
public function onProductListingResult(ProductListingResultEvent $event)
{
$route = $event->getRequest()->attributes->get('_route');
$products = $event->getResult()->getEntities();
// fourtwosix-edit: customer login check removed
$isLoggedIn = false;
$currentCustomerGroupId = null;
foreach ($products as $product) {
$attachmentId = $this->attachmentService->getMatchAttachmentId(
$route,
$currentCustomerGroupId,
$isLoggedIn,
$product->getId()
);
$criteria = new Criteria();
$criteria->addFilter(new EqualsAnyFilter('id', $attachmentId));
$criteria->addFilter(new EqualsFilter('display', "3"));
$criteria->addSorting(new FieldSorting('position', FieldSorting::ASCENDING));
$attachments = $this->attachmentsRepository->search($criteria, $event->getContext());
if ($attachments->getTotal() > 0) {
$product->assign(
[
'KsAttachments' => [
'attachments' => $attachments
]
]
);
}
}
}
}