Class names and method signatures already explain what these classes do. Project guideline (CLAUDE.md): comments only when the WHY is non-obvious — implementation details belong in commits, not noise on top of every class. Kept the one comment that earns it: the (int) cast in HasUsage::cachedPostCount, which documents the load-bearing workaround for Laravel's Redis cache numeric optimisation.
85 lines
2.2 KiB
PHP
85 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Jobs\PostHog\SendEvent;
|
|
use App\Models\Account;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class PostHogService
|
|
{
|
|
public static function isEnabled(): bool
|
|
{
|
|
return (bool) config('services.posthog.enabled')
|
|
&& (bool) config('services.posthog.api_key');
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $properties
|
|
*/
|
|
public function capture(string $distinctId, string $event, array $properties = [], ?Account $account = null): void
|
|
{
|
|
if (! self::isEnabled()) {
|
|
return;
|
|
}
|
|
|
|
$payload = [
|
|
'distinctId' => $distinctId,
|
|
'event' => $event,
|
|
'properties' => $properties,
|
|
];
|
|
|
|
if ($account) {
|
|
$payload['properties']['$groups'] = ['account' => (string) $account->id];
|
|
$payload['properties']['account_id'] = (string) $account->id;
|
|
$payload['properties']['plan'] = $account->plan?->name;
|
|
}
|
|
|
|
$this->dispatch('capture', $payload);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $properties
|
|
*/
|
|
public function identify(string $distinctId, array $properties = []): void
|
|
{
|
|
if (! self::isEnabled()) {
|
|
return;
|
|
}
|
|
|
|
$this->dispatch('identify', [
|
|
'distinctId' => $distinctId,
|
|
'properties' => $properties,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $properties
|
|
*/
|
|
public function groupIdentify(string $groupType, string $groupKey, array $properties = []): void
|
|
{
|
|
if (! self::isEnabled()) {
|
|
return;
|
|
}
|
|
|
|
$this->dispatch('groupIdentify', [
|
|
'groupType' => $groupType,
|
|
'groupKey' => $groupKey,
|
|
'properties' => $properties,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $payload
|
|
*/
|
|
private function dispatch(string $method, array $payload): void
|
|
{
|
|
try {
|
|
SendEvent::dispatch($method, $payload);
|
|
} catch (\Throwable $e) {
|
|
Log::warning('PostHogService: failed to dispatch event', ['method' => $method, 'error' => $e->getMessage()]);
|
|
}
|
|
}
|
|
}
|