<?php declare(strict_types=1);
namespace Wexo\ScriptManager\Subscriber;
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 Shopware\Storefront\Pagelet\Footer\FooterPageletLoadedEvent;
use Shopware\Storefront\Pagelet\Header\HeaderPageletLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Wexo\ScriptManager\Core\Content\ScriptManager\ScriptManagerEntity;
class scriptManagerSubscriber implements EventSubscriberInterface
{
/** @var EntityRepositoryInterface */
private $scriptManagerRepository;
public function __construct(
EntityRepositoryInterface $scriptManagerRepository
) {
$this->scriptManagerRepository = $scriptManagerRepository;
}
public static function getSubscribedEvents(): array
{
return [
HeaderPageletLoadedEvent::class => "scriptManagerHeader",
FooterPageletLoadedEvent::class => "scriptManagerFooter"
];
}
public function scriptManagerHeader(HeaderPageletLoadedEvent $event): void
{
$siteSalesChannelId = $this->getSalesChannelId($event);
$scriptList = $this->getCriteria('Header', $event);
$event->getPagelet()->scripts = $this->createScriptList($scriptList, $siteSalesChannelId);
}
public function scriptManagerFooter(FooterPageletLoadedEvent $event): void
{
$siteSalesChannelId = $this->getSalesChannelId($event);
$scriptList = $this->getCriteria('Footer', $event);
$event->getPagelet()->scripts = $this->createScriptList($scriptList, $siteSalesChannelId);
}
/**
* @param $location
* @param $event
* @return \Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult
*/
public function getCriteria($location, $event)
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
$criteria->addFilter(new EqualsFilter('location', $location));
$criteria->addSorting(new FieldSorting('priority', FieldSorting::DESCENDING));
return $this->scriptManagerRepository->search($criteria, $event->getContext());
}
/** Function to get sales channel id from $event
* @param $event
* @return
*/
private function getSalesChannelId($event)
{
return $event->getSalesChannelContext()->getSalesChannel()->getId();
}
/** Function to remove all scripts that is not matched with the current sales channel, as they should not be shown
* @param $scriptList
* @param $siteSalesChannelId
* @return array $scripts
*/
private function createScriptList($scriptList, $siteSalesChannelId)
{
$scripts = [];
/** @var ScriptManagerEntity $scriptEntity */
foreach ($scriptList->getElements() as $scriptEntity) {
if (in_array($siteSalesChannelId, $scriptEntity->getSalesChannel())) {
$scriptEntity->setScript(html_entity_decode($scriptEntity->getScript()));
array_push($scripts, $scriptEntity);
};
}
return $scripts;
}
}