<?php declare(strict_types=1);
/**
* (c) 2Hats Logic Solutions <info@2hatslogic.com>
*/
namespace Hatslogic\Sw\SearchKeywordHistory\Subscriber;
use Shopware\Core\Defaults;
use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\Routing\RouterInterface;
use Shopware\Storefront\Page\Search\SearchPageLoadedEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
class SearchSubscriber implements EventSubscriberInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var Connection
*/
private $connection;
/**
* @var RouterInterface
*/
private $router;
public function __construct(
ContainerInterface $container,
Connection $connection,
RouterInterface $router
) {
$this->container = $container;
$this->connection = $connection;
$this->router = $router;
}
public static function getSubscribedEvents(): array
{
return [
SearchPageLoadedEvent::class => 'onSearchPageLoaded'
];
}
public function onSearchPageLoaded(SearchPageLoadedEvent $event)
{
$request = $event->getRequest();
$searchKeyword = $request->get('search');
if(empty($searchKeyword))
{
return;
}
$keywordAlreadyExist = $this->getDetailsByKeyWord($searchKeyword);
if($keywordAlreadyExist)
{
//Update count and last search date
$params = [
'id' => $keywordAlreadyExist->getId(),
'searchCount' => $keywordAlreadyExist->getSearchCount() + 1,
'lastSearchAt' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
];
$this->updateCountAndLastSearchDate($params);
} else {
// Save
$params = [
'id' => Uuid::randomHex(),
'keyword' => $searchKeyword,
'searchCount' => 1,
'lastSearchAt' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
];
$this->saveSearchKeyWord($params);
}
return;
}
public function saveSearchKeyWord($params)
{
if(empty($params))
{
return;
}
$this->container->get('s_plugin_hatslogic_search_keywords.repository')
->create([$params], Context::createDefaultContext());
return;
}
public function getDetailsByKeyWord($keyword)
{
$criteria = (new Criteria())
->addFilter(new EqualsFilter(
's_plugin_hatslogic_search_keywords.keyword', $keyword));
$result = $this->container->get('s_plugin_hatslogic_search_keywords.repository')->search($criteria, Context::createDefaultContext());
$searchKeyWordDetails = $result->first();
return ($searchKeyWordDetails) ? $searchKeyWordDetails: null;
}
public function updateCountAndLastSearchDate($params)
{
if(empty($params))
{
return;
}
$this->container->get('s_plugin_hatslogic_search_keywords.repository')->update(
[
[
'id' => $params['id'],
'searchCount' => $params['searchCount'],
'lastSearchAt' => $params['lastSearchAt']
],
],
Context::createDefaultContext()
);
return true;
}
}