<?php
/**
* @license SILK SOFTWARE HOUSE SP Z O O
*/
namespace App\EventSubscriber;
use App\Decoder\Interfaces\DecoderInterface;
use App\Helpers\TimezoneHelper;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class RequestDecryptingSubscriber.
*/
class RequestDecryptingSubscriber implements EventSubscriberInterface
{
const MEASUREMENT_TIME = 'measurement_time';
const START_TIME = 'start_time';
const SERIAL_NUMBER = 'serial';
/**
* Decoder.
*
* @var DecoderInterface
*/
private $decoder;
/**
* Device ping path.
*
* @var string[]
*/
private $encryptedPaths;
/**
* @var LoggerInterface
*/
private $logger;
/**
* RequestDecryptingSubscriber constructor.
*
* @param DecoderInterface $decoder
* @param string[] $encryptedPaths Array of encrypted paths.
*/
public function __construct(DecoderInterface $decoder, array $encryptedPaths, LoggerInterface $logger)
{
$this->decoder = $decoder;
$this->encryptedPaths = $encryptedPaths;
}
/**
* Get subscribed events.
*
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onKernelRequest', 9999],
],
];
}
/**
* On kernel request.
*
* @param RequestEvent $event
*
* @throws AccessDeniedHttpException
*/
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$event->isMasterRequest() || !in_array($event->getRequest()->getPathInfo(), $this->encryptedPaths)) {
return;
}
$request->headers->set('accept', 'application/ld+json');
$request->headers->set('content-type', 'application/ld+json');
$decrypted = $this->decoder->decrypt($request->getContent())
?? $this->decoder->decrypt($request->getContent(), ['non-json' => true]);
if (null === $decrypted) {
throw new AccessDeniedHttpException();
}
foreach ($decrypted as $key => $value) {
$request->request->set($key, $value);
}
$timezoneHelper = new TimezoneHelper();
if (!isset($decrypted[self::SERIAL_NUMBER])) {
$request->request->set(
self::SERIAL_NUMBER,
$this->decoder->getLastCorrectPassword()
);
}
if (!empty($decrypted[self::MEASUREMENT_TIME])) {
$request->request->set(
self::MEASUREMENT_TIME,
$timezoneHelper->getCorrectedTime($decrypted[self::MEASUREMENT_TIME], $decrypted[self::START_TIME])
);
}
if (!empty($decrypted[self::START_TIME])) {
$request->request->set(
self::START_TIME,
$timezoneHelper->getCorrectedTime($decrypted[self::START_TIME], $decrypted[self::START_TIME])
);
}
}
}