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
6 changes: 6 additions & 0 deletions .changeset/three-pants-ask.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"posthog-php": minor
Comment thread
ioannisj marked this conversation as resolved.
Resolved
"posthog-laravel": minor
---

The new `getRemoteConfigPayload()` reads the payload of a remote config feature flag by its key, with no distinct ID. It needs the `secretKey` the client was created with. It returns `null` and logs a warning on a failure. Laravel exposes it through the `PostHog` facade.
18 changes: 18 additions & 0 deletions api/laravel-public-api.json
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,24 @@
}
]
},
"getRemoteConfigPayload": {
"static": false,
"abstract": false,
"final": false,
"returnType": "mixed",
"parameters": [
{
"name": "key",
"type": "string",
"byReference": false,
"variadic": false,
"optional": false,
"default": null,
"defaultConstant": null,
"hasDefault": false
}
]
},
"groupIdentify": {
"static": false,
"abstract": false,
Expand Down
36 changes: 36 additions & 0 deletions api/public-api.json
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,24 @@
"returnType": "?string",
"parameters": []
},
"getRemoteConfigPayload": {
"static": false,
"abstract": false,
"final": false,
"returnType": "mixed",
"parameters": [
{
"name": "key",
"type": "string",
"byReference": false,
"variadic": false,
"optional": false,
"default": null,
"defaultConstant": null,
"hasDefault": false
}
]
},
"groupIdentify": {
"static": false,
"abstract": false,
Expand Down Expand Up @@ -4836,6 +4854,24 @@
}
]
},
"getRemoteConfigPayload": {
"static": true,
"abstract": false,
"final": false,
"returnType": "mixed",
"parameters": [
{
"name": "key",
"type": "string",
"byReference": false,
"variadic": false,
"optional": false,
"default": null,
"defaultConstant": null,
"hasDefault": false
}
]
},
"groupIdentify": {
"static": true,
"abstract": false,
Expand Down
88 changes: 88 additions & 0 deletions lib/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,9 @@ private function doGetFeatureFlagResult(
* `$flags->getFlagPayload($key)` instead. This consolidates flag evaluation into a single
* `/flags` request per incoming request.
*
* A remote config flag with an encrypted payload is not available here; use
* `getRemoteConfigPayload()` for it.
*
* @param string $key Feature flag key.
* @param string|null $distinctId Defaults to the current request context distinctId, when set.
* @param array<string, mixed> $groups Group identifiers for group-based flags.
Expand Down Expand Up @@ -1225,6 +1228,91 @@ public function getFeatureFlagPayload(
return $result?->getPayload();
}

/**
* Fetch the payload of a remote config feature flag by key, with no distinct ID. Use this
* instead of `evaluateFlags()->getFlagPayload()` (or the deprecated `getFeatureFlagPayload()`)
* for a remote config flag, and always when its payload is encrypted: flag evaluation leaves a
* remote config flag with an encrypted payload out of its response. Needs the `secretKey` the
* client was created with. A Personal API Key returns an encrypted payload decrypted, and a
* Project Secret API Key returns it redacted.
*
* The call sends one request, with no retry, and captures no
* `$feature_flag_called` event. It logs a warning and returns null when the client is disabled,
* when no secret key is set, when the key is empty, `.` or `..`, when the request fails, or when
* PostHog answers with a non-2xx status. An empty response means the flag has no payload: the
* call returns null without a warning.
*
* @param string $key Feature flag key.
* @return mixed The decoded payload, or null when no payload could be read.
*/
public function getRemoteConfigPayload(string $key): mixed
{
if (!$this->enabled) {
$this->logWarning('The client is disabled');
return null;
}

if ($this->secretKey === null) {
$this->logWarning('A secret key is required to fetch a remote config payload from PostHog');
return null;
}

if (in_array($key, ['', '.', '..'], true)) {
$this->logWarning('A feature flag key is required to fetch a remote config payload from PostHog');
return null;
}

$response = $this->httpClient->sendRequest(
'/api/projects/@current/feature_flags/' . rawurlencode($key)
. '/remote_config?token=' . rawurlencode($this->apiKey),
null,
[
"User-Agent: " . $this->options['library_name'] . "/" . $this->options['library_version'],
"Authorization: Bearer " . $this->secretKey
],
[
'shouldRetry' => false,
'timeout' => $this->featureFlagsRequestTimeout
]
);

$code = $response->getResponseCode();
// cURL keeps the 2xx status when the transfer fails after the headers arrive.
$curlErrno = $response->getCurlErrno();
if ($curlErrno !== 0 || $code < 200 || $code >= 300) {
error_log(
'[PostHog][Client] Unable to fetch remote config payload: '
. ($curlErrno !== 0 || $code === 0
? 'connection error (curl errno ' . $curlErrno . ')'
: 'HTTP ' . $code)
);
return null;
}

// PostHog answers a flag that has no payload with an empty 2xx body.
$body = (string) $response->getResponse();
if (trim($body) === '') {
return null;
Comment thread
ioannisj marked this conversation as resolved.
Resolved
}

try {
$result = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
Comment thread
ioannisj marked this conversation as resolved.
Resolved
} catch (\JsonException) {
error_log('[PostHog][Client] Unable to read remote config payload: invalid JSON response');
return null;
}

if (is_string($result)) {
try {
return json_decode($result, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return $result;
}
}

return $result;
}

/**
* get the feature flag value for this distinct id.
*
Expand Down
2 changes: 2 additions & 0 deletions lib/FeatureFlagEvaluations.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ public function getFlag(string $key): bool|string|null
/**
* Returns the decoded payload for a flag without recording access or firing a $feature_flag_called event.
* Returns null for unknown keys or flags without a payload.
* A remote config flag with an encrypted payload is not in the snapshot; use
* `Client::getRemoteConfigPayload()` for it.
*
* @param string $key Feature flag key.
* @return mixed
Expand Down
22 changes: 22 additions & 0 deletions lib/PostHog.php
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,9 @@ public static function getFeatureFlagResult(
* `$flags->getFlagPayload($key)` instead. This consolidates flag evaluation into a single
* `/flags` request per incoming request.
*
* A remote config flag with an encrypted payload is not available here; use
* `getRemoteConfigPayload()` for it.
*
* @param string $key
* @param string|null $distinctId Defaults to the current request context distinctId, when set.
* @param array<string, mixed> $groups
Expand All @@ -390,6 +393,25 @@ public static function getFeatureFlagPayload(
);
}

/**
* Fetch the payload of a remote config feature flag by key, with no distinct ID. Use this
* instead of `evaluateFlags()->getFlagPayload()` (or the deprecated `getFeatureFlagPayload()`)
* for a remote config flag, and always when its payload is encrypted: flag evaluation leaves a
* remote config flag with an encrypted payload out of its response. Needs the `secretKey`
* option.
*
* See Client::getRemoteConfigPayload() for the key types and failure behavior.
*
* @param string $key Feature flag key.
* @return mixed The decoded payload, or null when no payload could be read.
*/
public static function getRemoteConfigPayload(string $key): mixed
{
self::checkClient();

return self::$client->getRemoteConfigPayload($key);
}

/**
* Evaluate every feature flag for a distinct id in a single round trip and return a snapshot.
* When distinctId is omitted, the current request context distinctId is used if available.
Expand Down
21 changes: 20 additions & 1 deletion packages/laravel/src/PostHog.php
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,12 @@ public function getFeatureFlagResult(
], $distinctId);
}

/** @deprecated Use evaluateFlags()->getFlagPayload() instead. */
/**
* @deprecated Use evaluateFlags()->getFlagPayload() instead.
*
* A remote config flag with an encrypted payload is not available here; use
* getRemoteConfigPayload() for it.
*/
public function getFeatureFlagPayload(
string $key,
?string $distinctId = null,
Expand All @@ -314,6 +319,20 @@ public function getFeatureFlagPayload(
], $distinctId);
}

/**
* Fetch the payload of a remote config feature flag by key, with no distinct ID. Use this
* instead of `evaluateFlags()->getFlagPayload()` (or the deprecated `getFeatureFlagPayload()`)
* for a remote config flag, and always when its payload is encrypted: flag evaluation leaves a
* remote config flag with an encrypted payload out of its response. Needs `posthog.secret_key`
* (`POSTHOG_SECRET_KEY`).
*
* See \PostHog\Client::getRemoteConfigPayload() for the key types and failure behavior.
*/
public function getRemoteConfigPayload(string $key): mixed
{
return $this->client()->getRemoteConfigPayload($key);
}

public function getAllFlags(
?string $distinctId = null,
array $groups = [],
Expand Down
16 changes: 15 additions & 1 deletion packages/laravel/tests/ApiSurfaceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,25 @@ function ($path, $body) use (&$payload) {
$this->assertNull($client->getContext());
}

public function testRemoteConfigPayloadForwardsToTheClient(): void
{
$client = $this->createMock(Client::class);
$client->expects($this->once())->method('getRemoteConfigPayload')->with('banner')
->willReturn(['color' => 'blue']);
$manager = $this->getMockBuilder(PostHog::class)
->setConstructorArgs([$this->app])
->onlyMethods(['client'])
->getMock();
$manager->expects($this->once())->method('client')->willReturn($client);
$this->assertSame(['color' => 'blue'], $manager->getRemoteConfigPayload('banner'));
}

public function testSupportedForwardersKeepTheCoreParameterSignatures(): void
{
$methods = [
'isFeatureEnabled', 'getFeatureFlag', 'getFeatureFlagResult', 'getFeatureFlagPayload',
'getAllFlags', 'loadFlags', 'contextFromHeaders', 'captureException', 'evaluateFlags',
'getRemoteConfigPayload', 'getAllFlags', 'loadFlags', 'contextFromHeaders', 'captureException',
'evaluateFlags',
];
foreach ($methods as $method) {
$signature = static fn ($parameter) => [
Expand Down
20 changes: 19 additions & 1 deletion test/MockedHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ class MockedHttpClient extends \PostHog\HttpClient
private $batchEndpointResponse;
private $batchEndpointResponseCode;
private $batchEndpointCurlErrno;
private $remoteConfigEndpointResponse;
private $remoteConfigEndpointResponseCode;
private $remoteConfigEndpointCurlErrno;

public function __construct(
string $host,
Expand All @@ -47,7 +50,10 @@ public function __construct(
int $flagsEndpointCurlErrno = 0,
$batchEndpointResponse = '{"status":1}',
int $batchEndpointResponseCode = 200,
int $batchEndpointCurlErrno = 0
int $batchEndpointCurlErrno = 0,
$remoteConfigEndpointResponse = '{}',
int $remoteConfigEndpointResponseCode = 200,
int $remoteConfigEndpointCurlErrno = 0
) {
parent::__construct(
$host,
Expand All @@ -71,6 +77,9 @@ public function __construct(
$this->batchEndpointResponse = $batchEndpointResponse;
$this->batchEndpointResponseCode = $batchEndpointResponseCode;
$this->batchEndpointCurlErrno = $batchEndpointCurlErrno;
$this->remoteConfigEndpointResponse = $remoteConfigEndpointResponse;
$this->remoteConfigEndpointResponseCode = $remoteConfigEndpointResponseCode;
$this->remoteConfigEndpointCurlErrno = $remoteConfigEndpointCurlErrno;
}

/**
Expand Down Expand Up @@ -165,6 +174,15 @@ public function sendRequest(string $path, ?string $payload, array $extraHeaders
);
}

if (str_starts_with($path, "/api/projects/@current/feature_flags/")) {
return new HttpResponse(
$this->remoteConfigEndpointResponse,
$this->remoteConfigEndpointResponseCode,
null,
$this->remoteConfigEndpointCurlErrno
);
}

throw new \LogicException('Unexpected HTTP request in test: ' . $path);
}
}
Loading
Loading