<?php declare(strict_types=1);
namespace HuebertAccountAttributes\Subscriber;
use HuebertAccountAttributes\Core\Content\Download\DownloadEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AccountSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $downloadRepository;
public function __construct(EntityRepositoryInterface $downloadRepository)
{
$this->downloadRepository = $downloadRepository;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
GenericPageLoadedEvent::class => 'onGenericPageLoaded'
];
}
public function onGenericPageLoaded(GenericPageLoadedEvent $event) {
$requestUri = $event->getRequest()->getRequestUri();
if(strpos($requestUri, '/account') === false && strpos($requestUri, '/download/') === false) {
return true;
}
$context = $event->getContext();
$salesChannelContext = $event->getSalesChannelContext();
$customerGroup = $salesChannelContext->getCurrentCustomerGroup()->getName();
$page = $event->getPage();
$downloads = $this->downloadRepository->search(new Criteria(), $context)->getElements();
$customerDownloads = [];
/**
* @var DownloadEntity $download
*/
foreach($downloads as $download) {
$customerGroups = $this->getCustomerGroupsArray($download);
if(empty($download->getCustomerGroups())) {
$customerDownloads[] = $download->getName();
} else if (in_array($customerGroup, $customerGroups)) {
$customerDownloads[] = $download->getName();
}
}
if(!empty($customerDownloads)) {
$page->assign([
'huebert_downloads' => $customerDownloads
]);
}
return true;
}
/**
* @param DownloadEntity $download
* @return array
*/
private function getCustomerGroupsArray($download): ?array {
$customerGroups = $download->getCustomerGroups();
if(empty($customerGroups)) {
return null;
}
$customerGroupsArray = [];
if(strpos($customerGroups, ",") !== false) {
$customerGroupsExplode = explode(",", $customerGroups);
foreach($customerGroupsExplode as $customerGroup) {
$customerGroupsArray[] = ltrim(trim($customerGroup));
}
return $customerGroupsArray;
} else {
$customerGroupsArray[] = ltrim(trim($customerGroups));
return $customerGroupsArray;
}
}
private function replaceSonderzeichen($str): string {
$search = array("Ä", "Ö", "Ü", "ä", "ö", "ü", "ß", "´");
$replace = array("Ae", "Oe", "Ue", "ae", "oe", "ue", "ss", "");
return str_replace($search, $replace, $str);
}
}