<?php
namespace App\Admin\EventSubscriber;
use App\Admin\Repository\StdConfigRepository;
use EightPoints\Bundle\GuzzleBundle\Events\GuzzleEvents;
use EightPoints\Bundle\GuzzleBundle\Events\PostTransactionEvent;
use EightPoints\Bundle\GuzzleBundle\Events\PreTransactionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Psr\Log\LoggerInterface;
class ParrotSubscriber implements EventSubscriberInterface
{
/**
* @var string|null
*/
private ?string $token = null;
/**
* @string $token
*/
public function __construct(private LoggerInterface $logger, private StdConfigRepository $configs)
{
}
private function getToken()
{
if ($this->token === null)
{
$this->token = $this->configs->findOneBy(['machineName' => 'parrot_token'])?->getValue() ?? '';
}
return $this->token;
}
public static function getSubscribedEvents(): array
{
return [
GuzzleEvents::preTransactionFor('parrot') => 'onPreTransaction',
GuzzleEvents::postTransactionFor('parrot') => 'onPostTransaction'
];
}
/**
* @param PreTransactionEvent $event
*/
public function onPreTransaction(PreTransactionEvent $event)
{
$request = $event->getTransaction();
$this->logger->info("REQUEST: " . $request->getUri());
$this->logger->info("REQUEST: " . $request->getBody()->getContents());
$modifiedRequest = $request->withHeader('Authorization', 'Bearer ' . $this->getToken());
$event->setTransaction($modifiedRequest);
}
/**
* @param PostTransactionEvent $event
*/
public function onPostTransaction(PostTransactionEvent $event)
{
$response = $event->getTransaction();
if ($response !== null) {
$body = (string)($response?->getBody()?->getContents() ?? '');
if (($response?->getStatusCode() ?? 0) === Response::HTTP_OK)
{
$this->logger->info("RESPONSE: " . $body);
}
else
{
$this->logger->error("RESPONSE: status " . $response?->getStatusCode() . $body);
}
$response->getBody()->rewind();
} else {
$this->logger->error('No response from Parrot Service');
}
}
}
?>