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/great-groups-capture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"posthog-php": patch
---

Copy capture `groups` input to the `$groups` event property so grouped events are associated correctly.
5 changes: 5 additions & 0 deletions lib/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -295,13 +295,18 @@ public function capture(array $message)
{
$flagsSnapshot = $message["flags"] ?? null;
unset($message["flags"]);
$hasGroups = array_key_exists("groups", $message);

$usedGeneratedPersonlessDistinctId = false;
if ($this->shouldApplyCaptureContext($message)) {
$message = $this->applyCaptureContext($message, $usedGeneratedPersonlessDistinctId);
}
$message = $this->message($message);

if (!array_key_exists('$groups', $message) && $hasGroups) {
$message['$groups'] = $message['groups'];
}

if (array_key_exists('$groups', $message)) {
$message["properties"]['$groups'] = $message['$groups'];
}
Expand Down
41 changes: 41 additions & 0 deletions test/PostHogTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ private function getConsumer(Client $client): object
return $consumerProp->getValue($client);
}

private function firstBatchEvent(): array
{
foreach ($this->http_client->calls as $call) {
if (($call["path"] ?? null) === "/batch/") {
$decoded = json_decode($call["payload"], true);
return $decoded["batch"][0];
}
}

self::fail("Expected a /batch/ call to have been made");
}

private function withEnvApiKey(?string $apiKey, callable $callback): void
{
$previousApiKey = getenv(PostHog::ENV_API_KEY);
Expand Down Expand Up @@ -96,6 +108,14 @@ public static function initNoOpApiKeyCases(): array
];
}

public static function captureGroupsCases(): array
{
return [
'groups key' => ["groups"],
'$groups key' => ['$groups'],
];
}

public static function disabledClientNoRequestCases(): array
{
return [
Expand Down Expand Up @@ -499,6 +519,27 @@ public function testCapture(): void
);
}

/**
* @dataProvider captureGroupsCases
*/
public function testCaptureAddsGroupsProperty(string $groupsKey): void
{
self::assertTrue(
PostHog::capture(
array(
"distinctId" => "john",
"event" => "grouped event",
$groupsKey => array("team" => 1),
)
)
);
PostHog::flush();

$event = $this->firstBatchEvent();

self::assertSame(array("team" => 1), $event["properties"]['$groups']);
}

public function testCaptureFlushesOnNextEnqueueAfterDefaultFlushInterval(): void
{
$mockClock = new MockClock(new \DateTimeImmutable('2022-05-01 00:00:00'));
Expand Down
Loading