<?php declare(strict_types=1);
namespace Emz\ShippingPaymentIcons\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\Context;
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\Struct\ArrayEntity;
use Shopware\Storefront\Pagelet\Footer\FooterPageletLoadedEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;;
class Frontend implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $iconRepository;
/**
* @var EntityRepositoryInterface
*/
private $mediaRepository;
public function __construct(
EntityRepositoryInterface $iconRepository,
EntityRepositoryInterface $mediaRepository
) {
$this->iconRepository = $iconRepository;
$this->mediaRepository = $mediaRepository;
}
public static function getSubscribedEvents(): array
{
return [
FooterPageletLoadedEvent::class => 'onFooterLoaded',
ProductPageLoadedEvent::class => 'onProductLoaded'
];
}
public function onFooterLoaded(FooterPageletLoadedEvent $event)
{
$criteria = new Criteria();
$criteria
->addFilter(new EqualsFilter('activeFooter', true))
->addAssociation('media');
$icons = $this->getIcons($criteria, $event->getContext());
$event->getPagelet()->addExtension('emzShippingPaymentIcons', new ArrayEntity(['wrapper' => $icons]));
}
public function onProductLoaded(ProductPageLoadedEvent $event)
{
$criteria = new Criteria();
$criteria
->addFilter(new EqualsFilter('activeProduct', true))
->addAssociation('media');
$icons = $this->getIcons($criteria, $event->getContext());
$event->getPage()->addExtension('emzShippingPaymentIcons', new ArrayEntity(['wrapper' => $icons]));
}
private function getIcons(Criteria $criteria, Context $context)
{
$icons = $this->iconRepository->search($criteria, $context)->getElements();
if (!$icons) {
return[];
}
$returnIcons = [];
foreach ($icons as $icon) {
if (!$icon) {
continue;
}
$returnIcons[] = [
'src' => $icon->getMedia(),
'title' => $icon->getTranslation('title'),
'alt' => $icon->getTranslation('alt')
];
}
return $returnIcons;
}
}