<?php
namespace App\EventListener;
use App\Event\USTServicePayloadEvent;
use App\Logger\UstServiceTrafficLogger;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class USTServiceEventListener implements EventSubscriberInterface
{
private $trafficLoggingEnabled;
private $logger;
public function __construct(bool $trafficLoggingEnabled, UstServiceTrafficLogger $logger)
{
$this->trafficLoggingEnabled = $trafficLoggingEnabled;
$this->logger = $logger;
}
/**
* Logs traffic sent from mobile devices and UST service automatically.
*
* Note: If the route name is changed it should also be reflected here.
*
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMasterRequest()) {
// don't do anything if it's not the master request
return;
}
$request = $event->getRequest();
$route = $request->attributes->get('_route');
// Update package, called by mobile devices
if ($route == 'app_api_ibeaconlastseen_package') {
$this->logTrafficContent('package_log', $request->getContent());
}
// Update package, called by UST service
if ($route == 'app_api_ibeaconlastseen_update') {
$decoded = base64_decode($request->getContent());
$packages = json_decode($decoded, true);
$payload = json_encode($packages, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$this->logTrafficContent('update_request_log', $payload);
}
// Update post test completetion status, called by google form submission
if ($route == 'app_api_posttestcompletion_update') {
$this->logTrafficContent('test_update_request_log', $request->getContent());
}
}
/**
* Logs UST service traffic event raised by application code.
*
* @param USTServicePayloadEvent $event
*/
public function onPayloadEvent(USTServicePayloadEvent $event)
{
if ($this->trafficLoggingEnabled) {
$this->logTrafficContent(
$event->getCategory(),
$event->getPayload()
);
}
}
private function logTrafficContent($category, $payload)
{
if ($this->trafficLoggingEnabled) {
$this->logger->write($category, $payload);
}
}
public static function getSubscribedEvents()
{
return [
RequestEvent::class => 'onKernelRequest',
USTServicePayloadEvent::class => 'onPayloadEvent',
];
}
}