<?php
declare(strict_types = 1);
namespace GrimmTheme\Storefront\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\Content\Category\CategoryCollection;
use Shopware\Core\Content\Category\Service\NavigationLoaderInterface;
use Shopware\Core\Content\Category\Tree\Tree;
use Shopware\Core\Content\Category\Tree\TreeItem;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\HttpFoundation\Request;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Storefront\Event\RouteRequest\LanguageRouteRequestEvent;
use Shopware\Core\System\Language\LanguageCollection;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult;
use Shopware\Core\Framework\Struct\ArrayStruct;
class DefaultSalutationSubscriber implements EventSubscriberInterface {
/**
* @var SystemConfigService
*/
private $systemConfigService;
/**
* @var EntityRepositoryInterface
*/
private $salutationRepository;
public function __construct(
SystemConfigService $systemConfigService,
EntityRepositoryInterface $salutationRepository
) {
$this->systemConfigService = $systemConfigService;
$this->salutationRepository = $salutationRepository;
}
public static function getSubscribedEvents()
{
return [
GenericPageLoadedEvent::class => 'onGenericPageLoadedEvent'
];
}
public function onGenericPageLoadedEvent(GenericPageLoadedEvent $event) {
$salutationId = null;
if (!empty($this->systemConfigService->get('GrimmTheme.config.defaultSalutation'))) {
$salutationId = $this->systemConfigService->get('GrimmTheme.config.defaultSalutation');
}
$salutationCollection = $this->getSalutation($salutationId, $event->getSalesChannelContext());
// we can go through first here, because:
//
// either we access the only one we found with the set id
// or we just take a random one as first salutation and
// set it as default
if(count($salutationCollection) > 0 ) {
$event->getPage()->addExtension(
'Grimm_defaultSalutation',
new ArrayStruct([$salutationCollection->first()])
);
}
}
private function getSalutation(String $salutationId = null, SalesChannelContext $context):EntitySearchResult
{
$criteria = new Criteria();
if($salutationId) {
$criteria->addFilter(new EqualsFilter('id', $salutationId));
}
// EntitySearchResult
return $this->salutationRepository->search($criteria, $context->getContext());
}
}