Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bright-owls-filter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"posthog-php": minor
---

Add a before_send callback for modifying or dropping fully enriched events.
53 changes: 53 additions & 0 deletions lib/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ class Client implements FeatureFlagEvaluationsHost
* flush_interval_seconds?: int|float,
* compress_request?: bool|string,
* error_handler?: callable,
* before_send?: callable(array<string, mixed>): (array<string, mixed>|null),
* filename?: string,
* is_server?: bool,
* flag_definition_cache_provider?: FlagDefinitionCacheProvider,
Expand Down Expand Up @@ -394,9 +395,51 @@ public function capture(array $message)

unset($message["send_feature_flags"]);

$message = $this->applyBeforeSend($message);
if ($message === null) {
return false;
}

return $this->consumer->capture($message);
}

/**
* Run the configured before_send callback for a fully enriched capture event.
*
* @param array<string, mixed> $message
* @return array<string, mixed>|null
*/
private function applyBeforeSend(array $message): ?array
{
$beforeSend = $this->options['before_send'] ?? null;
if ($beforeSend === null) {
return $message;
}

if (!is_callable($beforeSend)) {
error_log('[PostHog][Client] before_send is not callable; sending original event');
return $message;
}

try {
$result = $beforeSend($message);
} catch (Throwable $e) {
error_log('[PostHog][Client] before_send callback threw; dropping event: ' . $e->getMessage());
return null;
}

if ($result === null) {
return null;
}

if (!is_array($result)) {
error_log('[PostHog][Client] before_send must return an array or null; sending original event');
return $message;
}

return $result;
}

/**
* Captures an exception as a PostHog error tracking event.
*
Expand Down Expand Up @@ -454,6 +497,11 @@ public function identify(array $message)
$message["event"] = '$identify';
unset($message["send_feature_flags"]);

$message = $this->applyBeforeSend($message);
if ($message === null) {
return false;
}

return $this->consumer->identify($message);
}

Expand Down Expand Up @@ -1804,6 +1852,11 @@ public function alias(array $message)
$message['distinct_id'] = null;
unset($message['alias']);

$message = $this->applyBeforeSend($message);
if ($message === null) {
return false;
}

return $this->consumer->alias($message);
}

Expand Down
1 change: 1 addition & 0 deletions lib/PostHog.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class PostHog
* flush_interval_seconds?: int|float,
* compress_request?: bool|string,
* error_handler?: callable,
* before_send?: callable(array<string, mixed>): (array<string, mixed>|null),
* filename?: string,
* flag_definition_cache_provider?: FlagDefinitionCacheProvider,
* error_tracking?: array{
Expand Down
170 changes: 170 additions & 0 deletions test/PostHogTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

use Exception;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use PostHog\Client;
use PostHog\Consumer\NoOp;
use PostHog\PostHog;
Expand Down Expand Up @@ -487,6 +488,175 @@ public function testBatchSizeOneFlushesImmediately(): void
$this->assertSame('/batch/', $httpClient->calls[0]['path']);
}

public function testBeforeSendCanModifyFullyEnrichedEvent(): void
{
$httpClient = new MockedHttpClient("app.posthog.com");
$sawFullyEnrichedEvent = false;
$client = new Client(
self::FAKE_API_KEY,
[
"batch_size" => 1,
"before_send" => function (array $event) use (&$sawFullyEnrichedEvent): array {
$sawFullyEnrichedEvent = isset(
$event['properties']['$lib'],
$event['properties']['$lib_version'],
$event['properties']['$lib_consumer'],
$event['properties']['$is_server']
);
unset($event['properties']['secret']);
$event['properties']['before_send'] = true;

return $event;
},
],
$httpClient,
null,
false
);

$this->assertTrue($client->capture([
"distinctId" => "john",
"event" => "Module PHP Event",
"properties" => ["secret" => "remove"],
]));

$this->assertTrue($sawFullyEnrichedEvent);
$payload = json_decode($httpClient->calls[0]['payload'], true);
$properties = $payload['batch'][0]['properties'];
$this->assertTrue($properties['before_send']);
$this->assertArrayNotHasKey('secret', $properties);
}

public function testBeforeSendCanDropEvent(): void
{
$httpClient = new MockedHttpClient("app.posthog.com");
$client = new Client(
self::FAKE_API_KEY,
["batch_size" => 1, "before_send" => static fn(array $event): ?array => null],
$httpClient,
null,
false
);

$this->assertFalse($client->capture([
"distinctId" => "john",
"event" => "Module PHP Event",
]));
$this->assertSame([], $httpClient->calls ?? []);
}
Comment thread
marandaneto marked this conversation as resolved.

public function testBeforeSendRunsForIdentify(): void
{
$httpClient = new MockedHttpClient("app.posthog.com");
$client = new Client(
self::FAKE_API_KEY,
[
"batch_size" => 1,
"before_send" => static function (array $event): array {
$event['properties']['before_send'] = true;
unset($event['properties']['secret']);
return $event;
},
],
$httpClient,
null,
false
);

$this->assertTrue($client->identify([
"distinctId" => "john",
"properties" => ["secret" => "remove"],
]));

$payload = json_decode($httpClient->calls[0]['payload'], true);
$event = $payload['batch'][0];
$this->assertSame('$identify', $event['event']);
$this->assertTrue($event['properties']['before_send']);
$this->assertArrayNotHasKey('secret', $event['properties']);
}

public function testBeforeSendRunsForAlias(): void
{
$httpClient = new MockedHttpClient("app.posthog.com");
$client = new Client(
self::FAKE_API_KEY,
[
"batch_size" => 1,
"before_send" => static function (array $event): array {
$event['properties']['before_send'] = true;
unset($event['properties']['secret']);
return $event;
},
],
$httpClient,
null,
false
);

$this->assertTrue($client->alias([
"distinctId" => "john",
"alias" => "anonymous-id",
"properties" => ["secret" => "remove"],
]));

$payload = json_decode($httpClient->calls[0]['payload'], true);
$event = $payload['batch'][0];
$this->assertSame('$create_alias', $event['event']);
$this->assertTrue($event['properties']['before_send']);
$this->assertArrayNotHasKey('secret', $event['properties']);
}

public function testBeforeSendThrowingCallbackDropsEvent(): void
{
$httpClient = new MockedHttpClient("app.posthog.com");
$client = new Client(
self::FAKE_API_KEY,
[
"batch_size" => 1,
"before_send" => static fn(array $event): array => throw new RuntimeException('before_send failed'),
],
$httpClient,
null,
false
);

$this->assertFalse($client->capture([
"distinctId" => "john",
"event" => "Module PHP Event",
]));
$this->assertSame([], $httpClient->calls ?? []);
}

/**
* @dataProvider invalidBeforeSendCases
*/
public function testBeforeSendInvalidCallbackPathsCaptureOriginalEvent(mixed $beforeSend): void
{
$httpClient = new MockedHttpClient("app.posthog.com");
$client = new Client(
self::FAKE_API_KEY,
["batch_size" => 1, "before_send" => $beforeSend],
$httpClient,
null,
false
);

$this->assertTrue($client->capture([
"distinctId" => "john",
"event" => "Module PHP Event",
"properties" => ["original" => true],
]));

$payload = json_decode($httpClient->calls[0]['payload'], true);
$this->assertTrue($payload['batch'][0]['properties']['original']);
}

public static function invalidBeforeSendCases(): iterable
{
yield 'returns non-array' => [static fn(array $event): string => 'invalid'];
yield 'not callable' => ['not-callable'];
}


/**
* @dataProvider facadeNoOpBeforeInitCases
Expand Down
Loading