src/EventsSubscriber/System/PostHogSubscriber.php line 47

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventsSubscriber\System;
  4. use PostHog\PostHog;
  5. use Symfony\Component\Console\ConsoleEvents;
  6. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. /**
  12.  * Boots the PostHog PHP SDK from config/packages/posthog.yaml and flushes queued events at the end of each request.
  13.  */
  14. final class PostHogSubscriber implements EventSubscriberInterface
  15. {
  16.     private bool $initialized false;
  17.     public function __construct(
  18.         private readonly string $apiKey,
  19.         private readonly string $host,
  20.         private readonly bool $debug,
  21.     ) {
  22.     }
  23.     public static function getSubscribedEvents(): array
  24.     {
  25.         return [
  26.             KernelEvents::REQUEST => ['onKernelRequest'1024],
  27.             KernelEvents::TERMINATE => 'onKernelTerminate',
  28.             ConsoleEvents::COMMAND => ['onConsoleCommand'1024],
  29.         ];
  30.     }
  31.     public function onKernelRequest(RequestEvent $event): void
  32.     {
  33.         if (!$event->isMainRequest()) {
  34.             return;
  35.         }
  36.         $this->initialize();
  37.     }
  38.     public function onConsoleCommand(ConsoleCommandEvent $event): void
  39.     {
  40.         $this->initialize();
  41.     }
  42.     public function onKernelTerminate(TerminateEvent $event): void
  43.     {
  44.         if (!$this->initialized) {
  45.             return;
  46.         }
  47.         PostHog::flush();
  48.     }
  49.     private function initialize(): void
  50.     {
  51.         if ($this->initialized) {
  52.             return;
  53.         }
  54.         PostHog::init(
  55.             $this->apiKey !== '' $this->apiKey null,
  56.             [
  57.                 'host' => $this->host,
  58.                 'debug' => $this->debug,
  59.             ],
  60.         );
  61.         $this->initialized true;
  62.     }
  63. }