-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathClient.php
More file actions
1618 lines (1438 loc) · 57.5 KB
/
Client.php
File metadata and controls
1618 lines (1438 loc) · 57.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace PostHog;
use Exception;
use PostHog\Consumer\File;
use PostHog\Consumer\ForkCurl;
use PostHog\Consumer\LibCurl;
use PostHog\Consumer\Socket;
use Symfony\Component\Clock\Clock;
const SIZE_LIMIT = 50_000;
/**
* PostHog PHP SDK client for event capture, user identification, feature flags, and error tracking.
*/
class Client implements FeatureFlagEvaluationsHost
{
private const CONSUMERS = [
"socket" => Socket::class,
"file" => File::class,
"fork_curl" => ForkCurl::class,
"lib_curl" => LibCurl::class,
];
/**
* @var string
*/
private $apiKey;
/**
* @var string
*/
private $personalAPIKey;
/**
* @var integer
*/
private $featureFlagsRequestTimeout;
/**
* Consumer object handles queueing and bundling requests to PostHog.
*
* @var Consumer
*/
protected $consumer;
/**
* @var HttpClient
*/
public $httpClient;
/**
* @var array
*/
public $featureFlags;
/**
* @var array
*/
public $groupTypeMapping;
/**
* @var array
*/
public $cohorts;
/**
* @var array
*/
public $featureFlagsByKey;
/**
* @var SizeLimitedHash
*/
public $distinctIdsFeatureFlagsReported;
/**
* @var string|null Cached ETag for feature flag definitions
*/
private $flagsEtag;
/**
* @var bool
*/
private $debug;
/**
* @var array<string, mixed>
*/
private $options;
/**
* @var array<string, bool>
*/
private array $missingDistinctIdWarnings = [];
/**
* Create a new PostHog client with your project's API key.
*
* @param string $apiKey Your project API key.
* @param array{
* host?: string,
* ssl?: bool,
* timeout?: int,
* verify_batch_events_request?: bool,
* feature_flag_request_timeout_ms?: int,
* maximum_backoff_duration?: int,
* consumer?: 'socket'|'file'|'fork_curl'|'lib_curl',
* debug?: bool,
* max_queue_size?: int,
* batch_size?: int,
* compress_request?: bool|string,
* error_handler?: callable,
* filename?: string,
* error_tracking?: array{
* enabled?: bool,
* capture_errors?: bool,
* excluded_exceptions?: list<class-string>,
* max_frames?: int,
* context_provider?: callable
* }
* } $options Client and consumer configuration options.
* @param HttpClient|null $httpClient Custom HTTP client, primarily for tests and advanced integrations.
* @param string|null $personalAPIKey Personal API key used to load local feature flag definitions.
* @param bool $loadFeatureFlags Whether to load local feature flag definitions during construction.
*/
public function __construct(
string $apiKey,
array $options = [],
?HttpClient $httpClient = null,
?string $personalAPIKey = null,
bool $loadFeatureFlags = true,
) {
$this->apiKey = trim($apiKey);
$this->personalAPIKey = StringNormalizer::normalizeOptional($personalAPIKey);
$this->options = $options;
$this->debug = $options["debug"] ?? false;
$this->options['host'] = StringNormalizer::normalizeHost($options['host'] ?? null);
if ($this->apiKey === '') {
error_log('[PostHog][Client] apiKey is empty after trimming whitespace; check your project API key');
}
$Consumer = self::CONSUMERS[$options["consumer"] ?? "lib_curl"];
$this->consumer = new $Consumer($this->apiKey, $this->options, $httpClient);
$this->httpClient = $httpClient !== null ? $httpClient : new HttpClient(
$this->options['host'],
$options['ssl'] ?? true,
(int) ($options['maximum_backoff_duration'] ?? 10000),
false,
$options["debug"] ?? false,
null,
(int) ($options['timeout'] ?? 10000)
);
$this->featureFlagsRequestTimeout = (int) ($options['feature_flag_request_timeout_ms'] ?? 3000);
$this->featureFlags = [];
$this->groupTypeMapping = [];
$this->cohorts = [];
$this->featureFlagsByKey = [];
$this->distinctIdsFeatureFlagsReported = new SizeLimitedHash(SIZE_LIMIT);
$this->flagsEtag = null;
ExceptionCapture::configure($this, $options['error_tracking'] ?? []);
// Populate featureflags and grouptypemapping if possible
if (
count($this->featureFlags) == 0
&& !is_null($this->personalAPIKey)
&& $loadFeatureFlags
) {
$this->loadFlags();
}
}
/**
* Flush and clean up the underlying consumer when the client is destroyed.
*/
public function __destruct()
{
$this->consumer->__destruct();
}
/**
* Captures a user action.
*
* @param array{
* event: string,
* distinctId?: string,
* distinct_id?: string,
* properties?: array<string, mixed>,
* groups?: array<string, mixed>,
* timestamp?: mixed,
* flags?: FeatureFlagEvaluations,
* send_feature_flags?: bool,
* sendFeatureFlags?: bool
* } $message Event payload. `send_feature_flags` and `sendFeatureFlags` are deprecated; pass
* a `flags` snapshot from evaluateFlags() instead.
* @return bool Whether the capture call succeeded.
*/
public function capture(array $message)
{
$flagsSnapshot = $message["flags"] ?? null;
unset($message["flags"]);
$usedGeneratedPersonlessDistinctId = false;
if ($this->shouldApplyCaptureContext($message)) {
$message = $this->applyCaptureContext($message, $usedGeneratedPersonlessDistinctId);
}
$message = $this->message($message);
$message["type"] = "capture";
if (array_key_exists('$groups', $message)) {
$message["properties"]['$groups'] = $message['$groups'];
}
if ($flagsSnapshot instanceof FeatureFlagEvaluations) {
// Precedence: an explicit `flags` snapshot always wins over `send_feature_flags`. The
// snapshot guarantees the event carries the same values the developer branched on, with
// no additional /flags request.
if (!empty($message["send_feature_flags"])) {
error_log(
"[PostHog][Client] Both `flags` and `send_feature_flags` were passed to "
. "capture(); using `flags` and ignoring `send_feature_flags`."
);
}
$message["properties"] = array_merge(
$flagsSnapshot->getEventProperties(),
$message["properties"]
);
} elseif (array_key_exists("send_feature_flags", $message) && $message["send_feature_flags"]) {
trigger_error(
'capture()\'s `send_feature_flags` option is deprecated and will be removed in a '
. 'future major version. Pass a `flags` snapshot from Client::evaluateFlags(...) '
. 'instead — it avoids a second /flags request per capture and guarantees the '
. 'event carries the exact flag values your code branched on.',
E_USER_DEPRECATED
);
if (!$usedGeneratedPersonlessDistinctId) {
$extraProperties = [];
$flags = [];
if (count($this->featureFlags) != 0) {
// Local evaluation is enabled, flags are loaded, so try and get all flags
// we can without going to the server.
$flags = $this->getAllFlags($message["distinct_id"], $message["groups"], [], [], true);
} else {
$flags = $this->fetchFeatureVariants($message["distinct_id"], $message["groups"]);
}
// Add all feature variants to event
foreach ($flags as $flagKey => $flagValue) {
$extraProperties[sprintf('$feature/%s', $flagKey)] = $flagValue;
}
// Add all feature flag keys that aren't false to $active_feature_flags
// decide v2 does this automatically, but we need it for when we upgrade to v3
$extraProperties['$active_feature_flags'] = array_keys(array_filter($flags, function ($flagValue) {
return $flagValue !== false;
}));
$message["properties"] = array_merge($extraProperties, $message["properties"]);
}
}
return $this->consumer->capture($message);
}
/**
* Captures an exception as a PostHog error tracking event.
*
* @param \Throwable|string $exception The exception to capture or a plain string message
* @param string|null $distinctId User ID; a random UUID is used when omitted (no person profile created)
* @param array $additionalProperties Extra properties merged into the event
* @return bool whether the capture call succeeded
*/
public function captureException(
\Throwable|string $exception,
?string $distinctId = null,
array $additionalProperties = []
): bool {
$errorTrackingConfig = $this->options['error_tracking'] ?? [];
$maxFrames = max(0, (int) ($errorTrackingConfig['max_frames'] ?? 20));
$exceptionList = ExceptionPayloadBuilder::buildExceptionList($exception, $maxFrames);
if (empty($exceptionList)) {
return false;
}
$properties = array_merge(
$additionalProperties,
[
'$exception_list' => $exceptionList,
'$exception_handled' => ExceptionPayloadBuilder::getPrimaryHandled($exceptionList),
]
);
$message = [
'event' => '$exception',
'properties' => $properties,
];
if ($distinctId !== null) {
$message['distinctId'] = $distinctId;
}
return $this->capture($message);
}
/**
* Tags properties about the user.
*
* @param array{distinctId?: string, distinct_id?: string, properties?: array<string, mixed>} $message
* @return bool Whether the identify call succeeded.
*/
public function identify(array $message)
{
if (isset($message['properties'])) {
$message['$set'] = $message['properties'];
}
$message = $this->message($message);
$message["type"] = "identify";
$message["event"] = '$identify';
return $this->consumer->identify($message);
}
/**
* @deprecated Use `evaluateFlags($distinctId, ...)` and call
* `$flags->isEnabled($key)` instead. This consolidates flag evaluation into a single
* `/flags` request per incoming request.
*
* @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.
* @param array<string, mixed> $personProperties Person properties to use for flag evaluation.
* @param array<string, array<string, mixed>> $groupProperties Group properties to use for flag evaluation.
* @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback.
* @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events.
* @return bool|null
* @throws Exception
*/
public function isFeatureEnabled(
string $key,
?string $distinctId = null,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array(),
bool $onlyEvaluateLocally = false,
bool $sendFeatureFlagEvents = true
): null | bool {
trigger_error(
'Client::isFeatureEnabled() is deprecated and will be removed in a future major '
. 'version. Use Client::evaluateFlags($distinctId, ...) and call '
. '$flags->isEnabled($key) instead — this consolidates flag evaluation into a '
. 'single /flags request per incoming request.',
E_USER_DEPRECATED
);
// Route through the private helper so the user sees exactly one deprecation warning
// per call, not two (or three).
$result = $this->doGetFeatureFlagResult(
$key,
$distinctId,
$groups,
$personProperties,
$groupProperties,
$onlyEvaluateLocally,
$sendFeatureFlagEvents
);
if ($result === null) {
return null;
}
return boolval($result->getValue());
}
/**
* @deprecated Use `evaluateFlags($distinctId, ...)` and call
* `$flags->getFlag($key)` instead. This consolidates flag evaluation into a single
* `/flags` request per incoming request.
*
* @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.
* @param array<string, mixed> $personProperties Person properties to use for flag evaluation.
* @param array<string, array<string, mixed>> $groupProperties Group properties to use for flag evaluation.
* @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback.
* @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events.
* @return bool|string|null
* @throws Exception
*/
public function getFeatureFlag(
string $key,
?string $distinctId = null,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array(),
bool $onlyEvaluateLocally = false,
bool $sendFeatureFlagEvents = true
): null | bool | string {
trigger_error(
'Client::getFeatureFlag() is deprecated and will be removed in a future major '
. 'version. Use Client::evaluateFlags($distinctId, ...) and call '
. '$flags->getFlag($key) instead — this consolidates flag evaluation into a '
. 'single /flags request per incoming request.',
E_USER_DEPRECATED
);
// Route through the private helper so the user sees exactly one deprecation warning.
$result = $this->doGetFeatureFlagResult(
$key,
$distinctId,
$groups,
$personProperties,
$groupProperties,
$onlyEvaluateLocally,
$sendFeatureFlagEvents
);
return $result?->getValue();
}
/**
* @deprecated Use `evaluateFlags($distinctId, ...)` and call `$flags->getFlag($key)` and
* `$flags->getFlagPayload($key)` instead. This consolidates flag evaluation into a single
* `/flags` request per incoming request.
*
* @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.
* @param array<string, mixed> $personProperties Person properties to use for flag evaluation.
* @param array<string, array<string, mixed>> $groupProperties Group properties to use for flag evaluation.
* @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback.
* @param bool $sendFeatureFlagEvents Whether to send $feature_flag_called events.
* @return FeatureFlagResult|null
* @throws Exception
*/
public function getFeatureFlagResult(
string $key,
?string $distinctId = null,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array(),
bool $onlyEvaluateLocally = false,
bool $sendFeatureFlagEvents = true
): ?FeatureFlagResult {
trigger_error(
'Client::getFeatureFlagResult() is deprecated and will be removed in a future major '
. 'version. Use Client::evaluateFlags($distinctId, ...) and call $flags->getFlag($key) '
. '(and $flags->getFlagPayload($key) if you need the payload) instead — this '
. 'consolidates flag evaluation into a single /flags request per incoming request.',
E_USER_DEPRECATED
);
return $this->doGetFeatureFlagResult(
$key,
$distinctId,
$groups,
$personProperties,
$groupProperties,
$onlyEvaluateLocally,
$sendFeatureFlagEvents
);
}
/**
* Internal entry point for the rich single-flag fetch. Public callers should go through
* the deprecated `getFeatureFlagResult()`; the deprecated `isFeatureEnabled()` /
* `getFeatureFlag()` paths route directly here so a single user-level call surfaces exactly
* one deprecation warning, not two.
*
* @param array<string, mixed> $groups
* @param array<string, mixed> $personProperties
* @param array<string, array<string, mixed>> $groupProperties
* @throws Exception
*/
private function doGetFeatureFlagResult(
string $key,
?string $distinctId = null,
array $groups = [],
array $personProperties = [],
array $groupProperties = [],
bool $onlyEvaluateLocally = false,
bool $sendFeatureFlagEvents = true
): ?FeatureFlagResult {
$distinctId = $this->resolveDistinctId($distinctId);
if ($distinctId === '') {
$this->warnMissingDistinctId('Feature flag evaluation');
return null;
}
[$personProperties, $groupProperties] = $this->addLocalPersonAndGroupProperties(
$distinctId,
$groups,
$personProperties,
$groupProperties
);
$result = null;
$payload = null;
$featureFlagError = null;
foreach ($this->featureFlags as $flag) {
if ($flag["key"] == $key) {
try {
$result = $this->computeFlagLocally(
$flag,
$distinctId,
$groups,
$personProperties,
$groupProperties
);
} catch (RequiresServerEvaluationException $e) {
$result = null;
} catch (InconclusiveMatchException $e) {
$result = null;
} catch (Exception $e) {
$result = null;
error_log("[PostHog][Client] Error while computing variant:" . $e->getMessage());
}
}
}
$flagWasEvaluatedLocally = !is_null($result);
$requestId = null;
$evaluatedAt = null;
$flagDetail = null;
if (!$flagWasEvaluatedLocally && !$onlyEvaluateLocally) {
try {
$response = $this->fetchFlagsResponse($distinctId, $groups, $personProperties, $groupProperties);
$errors = [];
if (isset($response['errorsWhileComputingFlags']) && $response['errorsWhileComputingFlags']) {
$errors[] = FeatureFlagError::ERRORS_WHILE_COMPUTING_FLAGS;
}
$requestId = isset($response['requestId']) ? $response['requestId'] : null;
$evaluatedAt = isset($response['evaluatedAt']) ? $response['evaluatedAt'] : null;
$rawFlag = $response['flags'][$key] ?? null;
$flagDetail = ($rawFlag !== null && !($rawFlag['failed'] ?? false))
? $rawFlag
: null;
$featureFlags = $response['featureFlags'] ?? [];
if (array_key_exists($key, $featureFlags)) {
$result = $featureFlags[$key];
} else {
$errors[] = FeatureFlagError::FLAG_MISSING;
$result = null;
}
// Extract payload from response
$rawPayload = $response['featureFlagPayloads'][$key] ?? null;
if ($rawPayload !== null) {
$payload = json_decode($rawPayload, true);
}
if (!empty($errors)) {
$featureFlagError = implode(',', $errors);
}
} catch (HttpException $e) {
error_log("[PostHog][Client] Unable to get feature variants: " . $e->getMessage());
switch ($e->getErrorType()) {
case HttpException::QUOTA_LIMITED:
$featureFlagError = FeatureFlagError::QUOTA_LIMITED;
break;
case HttpException::TIMEOUT:
$featureFlagError = FeatureFlagError::TIMEOUT;
break;
case HttpException::CONNECTION_ERROR:
$featureFlagError = FeatureFlagError::CONNECTION_ERROR;
break;
case HttpException::API_ERROR:
$featureFlagError = FeatureFlagError::apiError($e->getStatusCode());
break;
default:
$featureFlagError = FeatureFlagError::UNKNOWN_ERROR;
}
$result = null;
} catch (Exception $e) {
error_log("[PostHog][Client] Unable to get feature variants: " . $e->getMessage());
$featureFlagError = FeatureFlagError::UNKNOWN_ERROR;
$result = null;
}
}
if ($sendFeatureFlagEvents) {
$properties = [
'$feature_flag' => $key,
'$feature_flag_response' => $result,
];
if (!is_null($requestId)) {
$properties['$feature_flag_request_id'] = $requestId;
}
if (!is_null($evaluatedAt)) {
$properties['$feature_flag_evaluated_at'] = $evaluatedAt;
}
if (!is_null($flagDetail)) {
$properties['$feature_flag_id'] = $flagDetail['metadata']['id'];
$properties['$feature_flag_version'] = $flagDetail['metadata']['version'];
$properties['$feature_flag_reason'] = $flagDetail['reason']['description'];
}
if (!is_null($featureFlagError)) {
$properties['$feature_flag_error'] = $featureFlagError;
}
$this->captureFlagCalledIfNeeded($distinctId, $key, $properties, $groups);
}
if (is_null($result)) {
return null;
}
// Determine enabled and variant from result
if (is_bool($result)) {
return new FeatureFlagResult($key, $result, null, $payload);
} else {
return new FeatureFlagResult($key, true, $result, $payload);
}
}
/**
* @deprecated Use `evaluateFlags($distinctId, ...)` and call
* `$flags->getFlagPayload($key)` instead. This consolidates flag evaluation into a single
* `/flags` request per incoming request.
*
* @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.
* @param array<string, mixed> $personProperties Person properties to use for flag evaluation.
* @param array<string, array<string, mixed>> $groupProperties Group properties to use for flag evaluation.
* @return mixed
*/
public function getFeatureFlagPayload(
string $key,
?string $distinctId = null,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array(),
): mixed {
trigger_error(
'Client::getFeatureFlagPayload() is deprecated and will be removed in a future major '
. 'version. Use Client::evaluateFlags($distinctId, ...) and call '
. '$flags->getFlagPayload($key) instead — this consolidates flag evaluation into a '
. 'single /flags request per incoming request.',
E_USER_DEPRECATED
);
// Route through the private helper so the user sees exactly one deprecation warning.
$result = $this->doGetFeatureFlagResult(
$key,
$distinctId,
$groups,
$personProperties,
$groupProperties,
false,
false
);
return $result?->getPayload();
}
/**
* get the feature flag value for this distinct id.
*
* @param string|null $distinctId Defaults to the current request context distinctId, when set.
* @param array<string, mixed> $groups Group identifiers for group-based flags.
* @param array<string, mixed> $personProperties Person properties to use for flag evaluation.
* @param array<string, array<string, mixed>> $groupProperties Group properties to use for flag evaluation.
* @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback.
* @return array<string, bool|string>
* @throws Exception
*/
public function getAllFlags(
?string $distinctId = null,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array(),
bool $onlyEvaluateLocally = false
): array {
$distinctId = $this->resolveDistinctId($distinctId);
if ($distinctId === '') {
$this->warnMissingDistinctId('getAllFlags()');
return [];
}
[$personProperties, $groupProperties] = $this->addLocalPersonAndGroupProperties(
$distinctId,
$groups,
$personProperties,
$groupProperties
);
$response = [];
$fallbackToFlags = false;
if (count($this->featureFlags) > 0) {
foreach ($this->featureFlags as $flag) {
try {
$response[$flag['key']] = $this->computeFlagLocally(
$flag,
$distinctId,
$groups,
$personProperties,
$groupProperties
);
} catch (RequiresServerEvaluationException $e) {
$fallbackToFlags = true;
} catch (InconclusiveMatchException $e) {
$fallbackToFlags = true;
} catch (Exception $e) {
$fallbackToFlags = true;
error_log("[PostHog][Client] Error while computing variant:" . $e->getMessage());
}
}
} else {
$fallbackToFlags = true;
}
if ($fallbackToFlags && !$onlyEvaluateLocally) {
try {
$featureFlags = $this->fetchFeatureVariants($distinctId, $groups, $personProperties, $groupProperties);
$response = array_merge($response, $featureFlags);
} catch (Exception $e) {
error_log("[PostHog][Client] Unable to get feature variants:" . $e->getMessage());
}
}
return $response;
}
/**
* Evaluate every feature flag for a distinct id in a single round trip and return a
* FeatureFlagEvaluations snapshot. When distinctId is omitted, the current request context
* distinctId is used if available. Reads on the snapshot do not trigger additional /flags
* requests; access via isEnabled() or getFlag() fires a deduped $feature_flag_called event the
* first time each key is touched.
*
* @param string|null $distinctId Defaults to the current request context distinctId, when set.
* @param array<string, mixed> $groups Group identifiers for group-based flags.
* @param array<string, mixed> $personProperties Person properties to use for flag evaluation.
* @param array<string, array<string, mixed>> $groupProperties Group properties to use for flag evaluation.
* @param bool $onlyEvaluateLocally Whether to avoid a remote /flags fallback.
* @param bool $disableGeoip Whether to disable GeoIP enrichment during remote evaluation.
* @param list<string>|null $flagKeys Optional list of flag keys. When provided, only these
* flags are evaluated — the underlying /flags request asks the server for just this
* subset, which makes the response smaller and the request cheaper. Use this when you
* only need a handful of flags out of many. Distinct from FeatureFlagEvaluations::only(),
* which scopes which already-evaluated flags get attached to a captured event.
* @return FeatureFlagEvaluations
*/
public function evaluateFlags(
?string $distinctId = null,
array $groups = [],
array $personProperties = [],
array $groupProperties = [],
bool $onlyEvaluateLocally = false,
bool $disableGeoip = false,
?array $flagKeys = null
): FeatureFlagEvaluations {
$distinctId = $this->resolveDistinctId($distinctId);
if ($distinctId === '') {
$this->warnMissingDistinctId('evaluateFlags()');
return new FeatureFlagEvaluations(
$distinctId,
[],
$groups,
$this,
);
}
[$personProperties, $groupProperties] = $this->addLocalPersonAndGroupProperties(
$distinctId,
$groups,
$personProperties,
$groupProperties
);
$records = [];
$requestId = null;
$evaluatedAt = null;
$errorsWhileComputing = false;
$quotaLimited = false;
$fallbackToRemote = false;
// Local pass: try to resolve any flag we can without going to the server. Track whether
// any flag was inconclusive (which forces a remote round trip) so we can skip /flags
// entirely when local evaluation covered everything we know about.
$hasLocalDefinitions = count($this->featureFlags) > 0;
if ($hasLocalDefinitions) {
$localKeys = [];
foreach ($this->featureFlags as $flag) {
$key = $flag['key'] ?? null;
if (!is_string($key) || $key === '') {
continue;
}
$localKeys[$key] = true;
if ($flagKeys !== null && !in_array($key, $flagKeys, true)) {
continue;
}
try {
$value = $this->computeFlagLocally(
$flag,
$distinctId,
$groups,
$personProperties,
$groupProperties
);
} catch (RequiresServerEvaluationException $e) {
$fallbackToRemote = true;
continue;
} catch (InconclusiveMatchException $e) {
$fallbackToRemote = true;
continue;
} catch (Exception $e) {
$fallbackToRemote = true;
error_log("[PostHog][Client] Error while computing variant: " . $e->getMessage());
continue;
}
$variant = is_string($value) ? $value : null;
$enabled = is_string($value) ? true : (bool) $value;
$id = isset($flag['id']) ? (int) $flag['id'] : null;
$records[$key] = new EvaluatedFlagRecord(
key: $key,
enabled: $enabled,
variant: $variant,
payload: null,
id: $id,
version: null,
reason: 'Evaluated locally',
locallyEvaluated: true,
);
}
// If the caller asked for keys we don't have local definitions for, hit /flags so
// we can resolve them.
if ($flagKeys !== null) {
foreach ($flagKeys as $requestedKey) {
if (!isset($localKeys[$requestedKey])) {
$fallbackToRemote = true;
break;
}
}
}
} else {
// No local definitions loaded — every flag has to come from the server.
$fallbackToRemote = true;
}
$shouldHitRemote = !$onlyEvaluateLocally && $fallbackToRemote;
if ($shouldHitRemote) {
try {
$response = $this->flags(
$distinctId,
$groups,
$personProperties,
$groupProperties,
$disableGeoip,
$flagKeys
);
$requestId = $response['requestId'] ?? null;
$evaluatedAt = isset($response['evaluatedAt']) && is_int($response['evaluatedAt'])
? $response['evaluatedAt']
: null;
$errorsWhileComputing = (bool) ($response['errorsWhileComputingFlags'] ?? false);
$remoteFlags = $response['flags'] ?? [];
foreach ($remoteFlags as $key => $flagDetail) {
if (!is_string($key) || $key === '' || isset($records[$key])) {
continue;
}
if (!is_array($flagDetail) || ($flagDetail['failed'] ?? false)) {
continue;
}
$variant = $flagDetail['variant'] ?? null;
$enabled = (bool) ($flagDetail['enabled'] ?? false);
// Payloads come down as JSON strings, but defensively handle pre-decoded
// values too (some clients/middleware may deserialize transparently).
$rawPayload = $flagDetail['metadata']['payload'] ?? null;
if ($rawPayload === null) {
$payload = null;
} elseif (is_string($rawPayload)) {
$payload = json_decode($rawPayload, true);
} else {
$payload = $rawPayload;
}
$records[$key] = new EvaluatedFlagRecord(
key: $key,
enabled: $enabled,
variant: is_string($variant) ? $variant : null,
payload: $payload,
id: isset($flagDetail['metadata']['id'])
? (int) $flagDetail['metadata']['id']
: null,
version: isset($flagDetail['metadata']['version'])
? (int) $flagDetail['metadata']['version']
: null,
reason: $flagDetail['reason']['description'] ?? null,
locallyEvaluated: false,
);
}
} catch (HttpException $e) {
if ($e->getErrorType() === HttpException::QUOTA_LIMITED) {
$quotaLimited = true;
}
error_log("[PostHog][Client] Unable to evaluate flags: " . $e->getMessage());
} catch (Exception $e) {
error_log("[PostHog][Client] Unable to evaluate flags: " . $e->getMessage());
}
}
return new FeatureFlagEvaluations(
$distinctId,
$records,
$groups,
$this,
$requestId,
$evaluatedAt,
null,
$errorsWhileComputing,
$quotaLimited,
);
}
/**
* Fire a $feature_flag_called event the first time a (flag key, distinct id) pair is seen by
* this Client, deduped via the per-distinct_id cache shared with every other flag-reading code
* path. Properties are built by the caller so each call site can shape the payload to match its
* available metadata.
*
* @param string $distinctId The distinct ID that accessed the flag.
* @param string $key Feature flag key.
* @param array<string, mixed> $properties Event properties for the $feature_flag_called event.
* @param array<string, mixed> $groups Group identifiers for group-based flags.
* @return void
*/
public function captureFlagCalledIfNeeded(
string $distinctId,
string $key,
array $properties,
array $groups = []
): void {
if ($this->distinctIdsFeatureFlagsReported->contains($key, $distinctId)) {
return;
}
$this->capture([
'properties' => $properties,
'distinct_id' => $distinctId,
'event' => '$feature_flag_called',
'$groups' => $groups,
]);
$this->distinctIdsFeatureFlagsReported->add($key, $distinctId);
}
/**
* Emit a non-fatal SDK warning.
*
* @param string $message Warning message without the SDK prefix.
* @return void
*/
public function logWarning(string $message): void
{
error_log("[PostHog][Client] " . $message);
}
private function computeFlagLocally(
array $featureFlag,
string $distinctId,
array $groups = array(),
array $personProperties = array(),
array $groupProperties = array()
): bool | string {
// Create evaluation cache for flag dependencies
$evaluationCache = [];
if ($featureFlag["ensure_experience_continuity"] ?? false) {
throw new InconclusiveMatchException("Flag has experience continuity enabled");
}
if (!$featureFlag["active"]) {
return false;
}
$flagFilters = $featureFlag["filters"] ?? [];
$aggregationGroupTypeIndex = $flagFilters["aggregation_group_type_index"] ?? null;