posthog-1.0.0-alpha5/src/CookieReader.php
src/CookieReader.php
<?php
declare(strict_types=1);
namespace Drupal\posthog;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Service for reading PostHog cookies.
*/
class CookieReader {
/**
* Constructs a CookieReader object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
* The config factory.
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
* The request stack.
*/
public function __construct(
protected readonly ConfigFactoryInterface $configFactory,
protected readonly RequestStack $requestStack,
) {}
/**
* Gets the whole PostHog cookie.
*
* @return string|null
* The cookie value or NULL if not found.
*/
public function getDecodedCookie(): ?array {
$request = $this->requestStack->getCurrentRequest();
if (empty($request)) {
return NULL;
}
$cookieName = $this->getCookieName();
$cookie = $request->cookies->get($cookieName);
if (empty($cookie)) {
return NULL;
}
return Json::decode($cookie);
}
/**
* Gets the PostHog cookie name based on the API key.
*
* @return string
* The cookie name.
*/
public function getCookieName(): string {
$config = $this->configFactory->get('posthog.settings');
$apiKey = $config->get('api_key');
if (empty($apiKey)) {
throw new \Exception('API key is not set in the configuration.');
}
return 'ph_' . $apiKey . '_posthog';
}
/**
* Extracts the distinct ID from the PostHog cookie.
*
* Note, that even if we don't identify the user javascript-wise, we will
* still receive a cookie with a distinct id.
*
* @return string|null
* The distinct ID or NULL if not found or extraction fails.
*/
public function getDistinctIdByCookie(): ?string {
$decodedCookie = $this->getDecodedCookie();
// Use the distinct id from the cookie, if it is set:
if (!empty($decodedCookie) && !empty($decodedCookie['distinct_id'])) {
return $decodedCookie['distinct_id'];
}
return NULL;
}
}
