Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Support For Feature Flag Payloads #53

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
43 changes: 42 additions & 1 deletion lib/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ class Client
*/
public $distinctIdsFeatureFlagsReported;

/**
* @var string
*/
public $decideVersion;

/**
* Create a new posthog object with your app's API key
* key
Expand Down Expand Up @@ -87,6 +92,7 @@ public function __construct(
$this->featureFlags = [];
$this->groupTypeMapping = [];
$this->distinctIdsFeatureFlagsReported = new SizeLimitedHash(SIZE_LIMIT);
$this->decideVersion = $options["decide_version"] ?? '2';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey Elliot, instead of making this an option, force update everything to version 3, I'll make a major version release for PHP with your PR, since we are meant to move off of v2 anyway.


// Populate featureflags and grouptypemapping if possible
if (count($this->featureFlags) == 0 && !is_null($this->personalAPIKey)) {
Expand Down Expand Up @@ -261,6 +267,41 @@ public function getFeatureFlag(
return null;
}

/**
* @param string $key
* @param string $distinctId
* @param array $groups
* @param array $personProperties
* @param array $groupProperties
* @return mixed
*/
public function getFeatureFlagPayload(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only thing blocking a merge here is support for local evaluation -> since getFeatureFlag supports local evaluation, the payload should too.

You can copy the exact code from python: https://github.com/PostHog/posthog-python/blob/master/posthog/client.py#L602 - and compare the get_feature_flag function to the PHP equivalent - they're exactly the same (with some language specific quirks)

You can also then copy all the tests below this line: https://github.com/PostHog/posthog-python/pull/81/files#diff-0e2fa9949bd8d80eecebfa2ff9b994a1bc528fbb003c7e80d104e6d5b3c5f07fR1379-R1384 to make sure it works fine.

Let me know if any questions! :) If this is too much for your bandwidth, let me know too.

string $key,
string $distinctId,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array(),
): mixed {
$results = json_decode(
$this->decide($distinctId, $groups, $personProperties, $groupProperties),
true
);

if (isset($results['featureFlags'][$key]) === false || $results['featureFlags'][$key] !== true) {
return null;
}

$payload = $results['featureFlagPayloads'][$key] ?? null;

$json = json_decode($payload, true);

if (is_array($json)) {
return $json;
}

return $payload;
}

/**
* get the feature flag value for this distinct id.
*
Expand Down Expand Up @@ -425,7 +466,7 @@ public function decide(
}

return $this->httpClient->sendRequest(
'/decide/?v=2',
'/decide/?v=' . $this->decideVersion,
json_encode($payload),
[
// Send user agent in the form of {library_name}/{library_version} as per RFC 7231.
Expand Down
26 changes: 25 additions & 1 deletion lib/PostHog.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,31 @@ public static function getFeatureFlag(
);
}

/**
/**
* @param string $key
* @param string $distinctId
* @param array $groups
* @param array $personProperties
* @param array $groupProperties
* @return mixed
*/
public static function getFeatureFlagPayload(
string $key,
string $distinctId,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array(),
): mixed {
return self::$client->getFeatureFlagPayload(
$key,
$distinctId,
$groups,
$personProperties,
$groupProperties
);
}

/**
* get all enabled flags for distinct_id
*
* @param string $distinctId
Expand Down
117 changes: 114 additions & 3 deletions test/FeatureFlagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@

class FeatureFlagTest extends TestCase
{
const FAKE_API_KEY = "random_key";
protected const FAKE_API_KEY = "random_key";

protected $http_client;
protected $client;
protected Client $client;

protected MockedHttpClient $http_client;

public function setUp(): void
{
Expand Down Expand Up @@ -2926,4 +2927,114 @@ public function testMultivariateFlagConsistency()
$this->assertEquals($testResult, $result[$number]);
}
}

public function testGetFeatureFlagPayloadHandlesJson(): void
{
$this->http_client = new MockedHttpClient(
host: "app.posthog.com",
flagEndpointResponse: MockedResponses::DECIDE_REQUEST_WITH_PAYLOAD_JSON
);

$this->client = new Client(
apiKey: self::FAKE_API_KEY,
options: [
"debug" => true,
"decide_version" => 3,
],
httpClient: $this->http_client,
personalAPIKey: "test"
);

PostHog::init(null, null, $this->client);

$this->assertSame(['key' => 'value'], PostHog::getFeatureFlagPayload('payload-flag', 'some-distinct'));
}

public function testGetFeatureFlagPayloadHandlesIntegers(): void
{
$this->http_client = new MockedHttpClient(
host: "app.posthog.com",
flagEndpointResponse: MockedResponses::DECIDE_REQUEST_WITH_PAYLOAD_INTEGER
);

$this->client = new Client(
apiKey: self::FAKE_API_KEY,
options: [
"debug" => true,
"decide_version" => 3,
],
httpClient: $this->http_client,
personalAPIKey: "test"
);

PostHog::init(null, null, $this->client);

$this->assertSame(2500, PostHog::getFeatureFlagPayload('payload-flag', 'some-distinct'));
}

public function testGetFeatureFlagPayloadHandlesString(): void
{
$this->http_client = new MockedHttpClient(
host: "app.posthog.com",
flagEndpointResponse: MockedResponses::DECIDE_REQUEST_WITH_PAYLOAD_STRING
);

$this->client = new Client(
apiKey: self::FAKE_API_KEY,
options: [
"debug" => true,
"decide_version" => 3,
],
httpClient: $this->http_client,
personalAPIKey: "test"
);

PostHog::init(null, null, $this->client);

$this->assertSame('A String', PostHog::getFeatureFlagPayload('payload-flag', 'some-distinct'));
}

public function testGetFeatureFlagPayloadHandlesFlagDisabled(): void
{
$this->http_client = new MockedHttpClient(
host: "app.posthog.com",
flagEndpointResponse: MockedResponses::DECIDE_REQUEST_WITH_PAYLOAD_JSON_FLAG_DISABLED
);

$this->client = new Client(
apiKey: self::FAKE_API_KEY,
options: [
"debug" => true,
"decide_version" => 3,
],
httpClient: $this->http_client,
personalAPIKey: "test"
);

PostHog::init(null, null, $this->client);

$this->assertNull(PostHog::getFeatureFlagPayload('payload-flag', 'some-distinct'));
}

public function testGetFeatureFlagPayloadHandlesFlagNotInResults(): void
{
$this->http_client = new MockedHttpClient(
host: "app.posthog.com",
flagEndpointResponse: MockedResponses::DECIDE_REQUEST_WITH_PAYLOAD_JSON
);

$this->client = new Client(
apiKey: self::FAKE_API_KEY,
options: [
"debug" => true,
"decide_version" => 3,
],
httpClient: $this->http_client,
personalAPIKey: "test"
);

PostHog::init(null, null, $this->client);

$this->assertNull(PostHog::getFeatureFlagPayload('non-existent-flag', 'some-distinct'));
}
}
2 changes: 1 addition & 1 deletion test/MockedHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function sendRequest(string $path, ?string $payload, array $extraHeaders
array_push($this->calls, array("path" => $path, "payload" => $payload));

if (str_starts_with($path, "/decide/")) {
return new HttpResponse(json_encode(MockedResponses::DECIDE_REQUEST), 200);
return new HttpResponse(json_encode($this->flagEndpointResponse ?? MockedResponses::DECIDE_REQUEST), 200);
}

if (str_starts_with($path, "/api/feature_flag/local_evaluation")) {
Expand Down
96 changes: 96 additions & 0 deletions test/assests/MockedResponses.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,102 @@ class MockedResponses
'sessionRecording' => false,
];

public const DECIDE_REQUEST_WITH_PAYLOAD_JSON = [
'config' => [
'enable_collect_everything' => true,
],
'editorParams' => [
],
'isAuthenticated' => false,
'supportedCompression' => [
0 => 'gzip',
1 => 'gzip-js',
2 => 'lz64',
],
'featureFlags' => [
'payload-flag' => true,
'having_fun' => false,
'enabled-flag' => true,
'disabled-flag' => false,
],
'sessionRecording' => false,
'featureFlagPayloads' => [
'payload-flag' => '{"key":"value"}',
]
];

public const DECIDE_REQUEST_WITH_PAYLOAD_JSON_FLAG_DISABLED = [
'config' => [
'enable_collect_everything' => true,
],
'editorParams' => [
],
'isAuthenticated' => false,
'supportedCompression' => [
0 => 'gzip',
1 => 'gzip-js',
2 => 'lz64',
],
'featureFlags' => [
'payload-flag' => false,
'having_fun' => false,
'enabled-flag' => true,
'disabled-flag' => false,
],
'sessionRecording' => false,
'featureFlagPayloads' => [
'payload-flag' => '{"key":"value"}',
]
];

public const DECIDE_REQUEST_WITH_PAYLOAD_INTEGER = [
'config' => [
'enable_collect_everything' => true,
],
'editorParams' => [
],
'isAuthenticated' => false,
'supportedCompression' => [
0 => 'gzip',
1 => 'gzip-js',
2 => 'lz64',
],
'featureFlags' => [
'payload-flag' => true,
'having_fun' => false,
'enabled-flag' => true,
'disabled-flag' => false,
],
'sessionRecording' => false,
'featureFlagPayloads' => [
'payload-flag' => 2500,
]
];

public const DECIDE_REQUEST_WITH_PAYLOAD_STRING = [
'config' => [
'enable_collect_everything' => true,
],
'editorParams' => [
],
'isAuthenticated' => false,
'supportedCompression' => [
0 => 'gzip',
1 => 'gzip-js',
2 => 'lz64',
],
'featureFlags' => [
'payload-flag' => true,
'having_fun' => false,
'enabled-flag' => true,
'disabled-flag' => false,
],
'sessionRecording' => false,
'featureFlagPayloads' => [
'payload-flag' => 'A String',
]
];

public const LOCAL_EVALUATION_REQUEST = [
'count' => 1,
'next' => null,
Expand Down