<?php
namespace Aqarmap\Bundle\ListingBundle\EventListener;
use Aqarmap\Bundle\ListingBundle\Event\SearchTriggerEvent;
use Aqarmap\Bundle\MainBundle\Constant\ProducerQueues;
use Aqarmap\Bundle\MainBundle\Contract\ProducerFactoryInterface;
use Aqarmap\Bundle\MainBundle\Service\MobileDetectionService;
use Aqarmap\Bundle\SearchBundle\Constant\SearchKeywordConstant;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class SearchKeywordHistorySubscriber implements EventSubscriberInterface
{
/**
* @var ProducerFactoryInterface
*/
private $producer;
private $source;
private $searchKeyword;
/**
* @var MobileDetectionService
*/
private $mobileService;
/**
* @var LoggerInterface
*/
private $logger;
/**
* SearchKeywordHistorySubscriber constructor.
*/
public function __construct(
ProducerFactoryInterface $producerFactory,
MobileDetectionService $mobileService,
LoggerInterface $logger
) {
$this->producer = $producerFactory->create(ProducerQueues::RECORD_KEYWORD_SEARCH_HISTORY);
$this->mobileService = $mobileService;
$this->logger = $logger;
}
/**
* Producer.
*/
public function onSearchKeyword(SearchTriggerEvent $searchTriggerEvent): void
{
try {
$this->setSource($searchTriggerEvent->getRequest());
$this->setSearchKeyword($searchTriggerEvent->getRequest());
if (!empty($this->getSearchKeyword())) {
$this
->producer
->publish(serialize([
'searchKeyword' => $this->getSearchKeyword(),
'userAgentOS' => $this->getSource(),
]))
;
}
} catch (\Exception $e) {
$this->logger->info($e->getMessage());
}
}
/**
* @param int
*/
public function getSource()
{
return $this->source;
}
/**
* @param string
*/
public function setSource(Request $request): self
{
$userAgent = $request->cookies->get('user-agent');
if (!$userAgent) {
$userAgent = $request->headers->get('user-agent');
}
$userAgentInfo = $this->mobileService->getInfo($userAgent);
switch ($userAgentInfo['os']) {
case SearchKeywordConstant::IOS_USER_AGENT_LABEL:
$this->source = SearchKeywordConstant::IOS_USER_AGENT;
break;
case SearchKeywordConstant::ANDROID_USER_AGENT_LABEL:
$this->source = SearchKeywordConstant::ANDROID_USER_AGENT;
break;
default:
$this->source = SearchKeywordConstant::WEB_USER_AGENT;
break;
}
return $this;
}
/**
* @param string
*/
public function getSearchKeyword()
{
return $this->searchKeyword;
}
public function setSearchKeyword(Request $request): self
{
$this->searchKeyword = trim((string) $request->query->get('keywordSearch'));
return $this;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
SearchTriggerEvent::class => 'onSearchKeyword',
];
}
}