<?php
declare(strict_types=1);
namespace App\EventsSubscriber\System;
use PostHog\PostHog;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Boots the PostHog PHP SDK from config/packages/posthog.yaml and flushes queued events at the end of each request.
*/
final class PostHogSubscriber implements EventSubscriberInterface
{
private bool $initialized = false;
public function __construct(
private readonly string $apiKey,
private readonly string $host,
private readonly bool $debug,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 1024],
KernelEvents::TERMINATE => 'onKernelTerminate',
ConsoleEvents::COMMAND => ['onConsoleCommand', 1024],
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$this->initialize();
}
public function onConsoleCommand(ConsoleCommandEvent $event): void
{
$this->initialize();
}
public function onKernelTerminate(TerminateEvent $event): void
{
if (!$this->initialized) {
return;
}
PostHog::flush();
}
private function initialize(): void
{
if ($this->initialized) {
return;
}
PostHog::init(
$this->apiKey !== '' ? $this->apiKey : null,
[
'host' => $this->host,
'debug' => $this->debug,
],
);
$this->initialized = true;
}
}