src/Admin/EventSubscriber/ParrotSubscriber.php line 62

Open in your IDE?
  1. <?php
  2. namespace App\Admin\EventSubscriber;
  3. use App\Admin\Repository\StdConfigRepository;
  4. use EightPoints\Bundle\GuzzleBundle\Events\GuzzleEvents;
  5. use EightPoints\Bundle\GuzzleBundle\Events\PostTransactionEvent;
  6. use EightPoints\Bundle\GuzzleBundle\Events\PreTransactionEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Psr\Log\LoggerInterface;
  10. class ParrotSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var string|null
  14.      */
  15.     private ?string $token null;
  16.     /**
  17.      * @string $token
  18.      */
  19.     public function __construct(private LoggerInterface $logger, private StdConfigRepository $configs)
  20.     {
  21.     }
  22.     private function getToken()
  23.     {
  24.         if ($this->token === null)
  25.         {
  26.             $this->token $this->configs->findOneBy(['machineName' => 'parrot_token'])?->getValue() ?? '';
  27.         }
  28.         return $this->token;
  29.     }
  30.     public static function getSubscribedEvents(): array
  31.     {
  32.         return [
  33.             GuzzleEvents::preTransactionFor('parrot') => 'onPreTransaction',
  34.             GuzzleEvents::postTransactionFor('parrot') => 'onPostTransaction'
  35.         ];
  36.     }
  37.     /**
  38.      * @param PreTransactionEvent $event
  39.      */
  40.     public function onPreTransaction(PreTransactionEvent $event)
  41.     {
  42.         $request $event->getTransaction();
  43.         $this->logger->info("REQUEST: " $request->getUri());
  44.         $this->logger->info("REQUEST: " $request->getBody()->getContents());
  45.         $modifiedRequest $request->withHeader('Authorization''Bearer ' $this->getToken());
  46.         $event->setTransaction($modifiedRequest);
  47.     }
  48.     
  49.     /**
  50.      * @param PostTransactionEvent $event
  51.      */
  52.     public function onPostTransaction(PostTransactionEvent $event)
  53.     {
  54.         $response $event->getTransaction();
  55.         if ($response !== null) {
  56.             $body = (string)($response?->getBody()?->getContents() ?? '');
  57.             if (($response?->getStatusCode() ?? 0) === Response::HTTP_OK)
  58.             {
  59.                 $this->logger->info("RESPONSE: " $body);
  60.             }
  61.             else
  62.             {
  63.                 $this->logger->error("RESPONSE: status " $response?->getStatusCode() . $body);
  64.             }
  65.             $response->getBody()->rewind();
  66.         } else {
  67.             $this->logger->error('No response from Parrot Service');
  68.         }
  69.     }
  70. }
  71. ?>