-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathFeatureFlag.php
More file actions
827 lines (710 loc) · 30.8 KB
/
FeatureFlag.php
File metadata and controls
827 lines (710 loc) · 30.8 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
<?php
namespace PostHog;
use Symfony\Component\Clock\Clock;
const LONG_SCALE = 0xfffffffffffffff;
class FeatureFlag
{
public static function matchProperty($property, $propertyValues)
{
$key = $property["key"];
$operator = $property["operator"] ?? "exact";
$value = $property["value"];
if (!array_key_exists($key, $propertyValues)) {
throw new InconclusiveMatchException("Can't match properties without a given property value");
}
if ($operator == "is_not_set") {
throw new InconclusiveMatchException("can't match properties with operator is_not_set");
}
$overrideValue = $propertyValues[$key];
if ($operator == "exact") {
return FeatureFlag::computeExactMatch($value, $overrideValue);
}
if ($operator == "is_not") {
return !FeatureFlag::computeExactMatch($value, $overrideValue);
}
if ($operator == "is_set") {
return array_key_exists($key, $propertyValues);
}
if ($operator == "icontains") {
return strpos(strtolower(FeatureFlag::valueToString($overrideValue)), strtolower(FeatureFlag::valueToString($value))) !== false;
}
if ($operator == "not_icontains") {
return strpos(strtolower(FeatureFlag::valueToString($overrideValue)), strtolower(FeatureFlag::valueToString($value))) == false;
}
if (in_array($operator, ["regex", "not_regex"])) {
$regexValue = FeatureFlag::prepareValueForRegex($value);
if (FeatureFlag::isRegularExpression($regexValue)) {
if ($overrideValue === null) {
return false;
}
$returnValue = preg_match($regexValue, $overrideValue) ? true : false;
if ($operator == "regex") {
return $returnValue;
} else {
return !$returnValue;
}
} else {
return false;
}
}
if (in_array($operator, ["gt", "gte", "lt", "lte"])) {
$parsedValue = null;
if (is_numeric($value)) {
$parsedValue = floatval($value);
}
if (!is_null($parsedValue) && !is_null($overrideValue)) {
if (is_string($overrideValue)) {
return FeatureFlag::compare($overrideValue, FeatureFlag::valueToString($value), $operator);
} else {
return FeatureFlag::compare($overrideValue, $parsedValue, $operator, "numeric");
}
} else {
return FeatureFlag::compare(FeatureFlag::valueToString($overrideValue), FeatureFlag::valueToString($value), $operator);
}
}
if (in_array($operator, ["is_date_before", "is_date_after"])) {
$parsedDate = FeatureFlag::relativeDateParseForFeatureFlagMatching($value);
if (is_null($parsedDate)) {
$parsedDate = FeatureFlag::convertToDateTime($value);
}
if (is_null($parsedDate)) {
throw new InconclusiveMatchException("The date set on the flag is not a valid format");
}
$overrideDate = FeatureFlag::convertToDateTime($overrideValue);
if ($operator == 'is_date_before') {
return $overrideDate < $parsedDate;
} else {
return $overrideDate > $parsedDate;
}
}
// Semver operators
if (in_array($operator, ["semver_eq", "semver_neq", "semver_gt", "semver_gte", "semver_lt", "semver_lte"])) {
$overrideTuple = FeatureFlag::parseSemver($overrideValue);
$valueTuple = FeatureFlag::parseSemver($value);
$comparison = FeatureFlag::compareSemverTuples($overrideTuple, $valueTuple);
if ($operator === "semver_eq") {
return $comparison === 0;
} elseif ($operator === "semver_neq") {
return $comparison !== 0;
} elseif ($operator === "semver_gt") {
return $comparison > 0;
} elseif ($operator === "semver_gte") {
return $comparison >= 0;
} elseif ($operator === "semver_lt") {
return $comparison < 0;
} elseif ($operator === "semver_lte") {
return $comparison <= 0;
}
}
if ($operator === "semver_tilde") {
$overrideTuple = FeatureFlag::parseSemver($overrideValue);
list($lower, $upper) = FeatureFlag::tildeBounds($value);
return FeatureFlag::compareSemverTuples($overrideTuple, $lower) >= 0
&& FeatureFlag::compareSemverTuples($overrideTuple, $upper) < 0;
}
if ($operator === "semver_caret") {
$overrideTuple = FeatureFlag::parseSemver($overrideValue);
list($lower, $upper) = FeatureFlag::caretBounds($value);
return FeatureFlag::compareSemverTuples($overrideTuple, $lower) >= 0
&& FeatureFlag::compareSemverTuples($overrideTuple, $upper) < 0;
}
if ($operator === "semver_wildcard") {
$overrideTuple = FeatureFlag::parseSemver($overrideValue);
list($lower, $upper) = FeatureFlag::wildcardBounds($value);
return FeatureFlag::compareSemverTuples($overrideTuple, $lower) >= 0
&& FeatureFlag::compareSemverTuples($overrideTuple, $upper) < 0;
}
return false;
}
public static function matchCohort($property, $propertyValues, $cohortProperties, $flagsByKey = null, $evaluationCache = null, $distinctId = null)
{
$cohortId = strval($property["value"]);
if (!array_key_exists($cohortId, $cohortProperties)) {
throw new RequiresServerEvaluationException(
"cohort {$cohortId} not found in local cohorts - " .
"likely a static cohort that requires server evaluation"
);
}
$propertyGroup = $cohortProperties[$cohortId];
return FeatureFlag::matchPropertyGroup($propertyGroup, $propertyValues, $cohortProperties, $flagsByKey, $evaluationCache, $distinctId);
}
public static function matchPropertyGroup($propertyGroup, $propertyValues, $cohortProperties, $flagsByKey = null, $evaluationCache = null, $distinctId = null)
{
if (!$propertyGroup) {
return true;
}
$propertyGroupType = $propertyGroup["type"];
$properties = $propertyGroup["values"];
if (!$properties || count($properties) === 0) {
// empty groups are no-ops, always match
return true;
}
$errorMatchingLocally = false;
if (array_key_exists("values", $properties[0])) {
// a nested property group
foreach ($properties as $prop) {
try {
$matches = FeatureFlag::matchPropertyGroup($prop, $propertyValues, $cohortProperties, $flagsByKey, $evaluationCache, $distinctId);
if ($propertyGroupType === 'AND') {
if (!$matches) {
return false;
}
} else {
// OR group
if ($matches) {
return true;
}
}
} catch (RequiresServerEvaluationException $err) {
// Immediately propagate - this condition requires server-side data
throw $err;
} catch (InconclusiveMatchException $err) {
$errorMatchingLocally = true;
}
}
if ($errorMatchingLocally) {
throw new InconclusiveMatchException("Can't match cohort without a given cohort property value");
}
// if we get here, all matched in AND case, or none matched in OR case
return $propertyGroupType === 'AND';
} else {
foreach ($properties as $prop) {
try {
$matches = false;
$propType = $prop["type"] ?? null;
if ($propType === 'cohort') {
$matches = FeatureFlag::matchCohort($prop, $propertyValues, $cohortProperties, $flagsByKey, $evaluationCache, $distinctId);
} elseif ($propType === 'flag') {
$matches = FeatureFlag::evaluateFlagDependency($prop, $flagsByKey, $evaluationCache, $distinctId, $propertyValues, $cohortProperties);
} else {
$matches = FeatureFlag::matchProperty($prop, $propertyValues);
}
$negation = $prop["negation"] ?? false;
if ($propertyGroupType === 'AND') {
// if negated property, do the inverse
if (!$matches && !$negation) {
return false;
}
if ($matches && $negation) {
return false;
}
} else {
// OR group
if ($matches && !$negation) {
return true;
}
if (!$matches && $negation) {
return true;
}
}
} catch (RequiresServerEvaluationException $err) {
// Immediately propagate - this condition requires server-side data
throw $err;
} catch (InconclusiveMatchException $err) {
// If this is a flag dependency error, preserve the original message
if ($propType === 'flag') {
throw $err;
}
$errorMatchingLocally = true;
}
}
if ($errorMatchingLocally) {
throw new InconclusiveMatchException("can't match cohort without a given cohort property value");
}
// if we get here, all matched in AND case, or none matched in OR case
return $propertyGroupType === 'AND';
}
}
public static function relativeDateParseForFeatureFlagMatching($value)
{
$regex = "/^-?(?<number>[0-9]+)(?<interval>[a-z])$/";
$parsedDt = \DateTime::createFromInterface(Clock::get()->now())->setTimezone(new \DateTimeZone("UTC"));
if (preg_match($regex, $value, $matches)) {
$number = intval($matches["number"]);
if ($number >= 10_000) {
// Guard against overflow, disallow numbers greater than 10_000
return null;
}
$interval = $matches["interval"];
if ($interval == "h") {
$parsedDt->sub(new \DateInterval("PT{$number}H"));
} elseif ($interval == "d") {
$parsedDt->sub(new \DateInterval("P{$number}D"));
} elseif ($interval == "w") {
$parsedDt->sub(new \DateInterval("P{$number}W"));
} elseif ($interval == "m") {
$parsedDt->sub(new \DateInterval("P{$number}M"));
} elseif ($interval == "y") {
$parsedDt->sub(new \DateInterval("P{$number}Y"));
} else {
return null;
}
return $parsedDt;
} else {
return null;
}
}
/**
* Parse a semver string into a tuple of [major, minor, patch].
*
* Rules:
* 1. Strip leading/trailing whitespace
* 2. Strip `v` or `V` prefix (e.g., "v1.2.3" → "1.2.3")
* 3. Strip pre-release and build metadata suffixes (split on `-` or `+`, take first part)
* 4. Split on `.` and parse first 3 components as integers
* 5. Default missing components to 0 (e.g., "1.2" → (1, 2, 0), "1" → (1, 0, 0))
* 6. Ignore extra components beyond the third (e.g., "1.2.3.4" → (1, 2, 3))
* 7. Throw InconclusiveMatchException for invalid input (empty string, non-numeric parts, leading dot)
*
* @param mixed $value The semver string to parse
* @return array{int, int, int} The parsed tuple [major, minor, patch]
* @throws InconclusiveMatchException If the value cannot be parsed as semver
*/
public static function parseSemver($value): array
{
if ($value === null || $value === "") {
throw new InconclusiveMatchException("Cannot parse empty or null value as semver");
}
$text = trim(strval($value));
if ($text === "") {
throw new InconclusiveMatchException("Cannot parse empty value as semver");
}
// Strip v/V prefix
$text = ltrim($text, "vV");
if ($text === "") {
throw new InconclusiveMatchException("Cannot parse semver: only prefix found");
}
// Strip pre-release and build metadata (split on - or +, take first part)
$text = preg_split('/[-+]/', $text, 2)[0];
// Check for leading dot
if (str_starts_with($text, ".")) {
throw new InconclusiveMatchException("Cannot parse semver with leading dot: {$value}");
}
// Split on dots
$parts = explode(".", $text);
// Parse major
if (!isset($parts[0]) || $parts[0] === "" || !ctype_digit(ltrim($parts[0], "0") ?: "0")) {
// Allow pure zeros or numeric strings
if (isset($parts[0]) && preg_match('/^[0-9]+$/', $parts[0])) {
$major = intval($parts[0]);
} else {
throw new InconclusiveMatchException("Cannot parse semver: invalid major version in {$value}");
}
} else {
$major = intval($parts[0]);
}
// Parse minor (default to 0 if not present or empty)
$minor = 0;
if (isset($parts[1]) && $parts[1] !== "") {
if (!preg_match('/^[0-9]+$/', $parts[1])) {
throw new InconclusiveMatchException("Cannot parse semver: invalid minor version in {$value}");
}
$minor = intval($parts[1]);
}
// Parse patch (default to 0 if not present or empty)
$patch = 0;
if (isset($parts[2]) && $parts[2] !== "") {
if (!preg_match('/^[0-9]+$/', $parts[2])) {
throw new InconclusiveMatchException("Cannot parse semver: invalid patch version in {$value}");
}
$patch = intval($parts[2]);
}
return [$major, $minor, $patch];
}
/**
* Compare two semver tuples.
*
* @param array{int, int, int} $a First tuple
* @param array{int, int, int} $b Second tuple
* @return int -1 if a < b, 0 if a == b, 1 if a > b
*/
private static function compareSemverTuples(array $a, array $b): int
{
if ($a[0] !== $b[0]) {
return $a[0] <=> $b[0];
}
if ($a[1] !== $b[1]) {
return $a[1] <=> $b[1];
}
return $a[2] <=> $b[2];
}
/**
* Calculate tilde bounds for semver matching.
* ~X.Y.Z means >=X.Y.Z and <X.(Y+1).0
*
* @param mixed $value The semver pattern
* @return array{array{int, int, int}, array{int, int, int}} [lower, upper] bounds
*/
private static function tildeBounds($value): array
{
$tuple = FeatureFlag::parseSemver($value);
$lower = $tuple;
$upper = [$tuple[0], $tuple[1] + 1, 0];
return [$lower, $upper];
}
/**
* Calculate caret bounds for semver matching.
* ^X.Y.Z where:
* - X > 0: >=X.Y.Z <(X+1).0.0
* - X == 0, Y > 0: >=0.Y.Z <0.(Y+1).0
* - X == 0, Y == 0: >=0.0.Z <0.0.(Z+1)
*
* @param mixed $value The semver pattern
* @return array{array{int, int, int}, array{int, int, int}} [lower, upper] bounds
*/
private static function caretBounds($value): array
{
$tuple = FeatureFlag::parseSemver($value);
$lower = $tuple;
if ($tuple[0] > 0) {
$upper = [$tuple[0] + 1, 0, 0];
} elseif ($tuple[1] > 0) {
$upper = [0, $tuple[1] + 1, 0];
} else {
$upper = [0, 0, $tuple[2] + 1];
}
return [$lower, $upper];
}
/**
* Calculate wildcard bounds for semver matching.
* X.Y.* means >=X.Y.0 <X.(Y+1).0
* X.* means >=X.0.0 <(X+1).0.0
*
* @param mixed $value The semver pattern with wildcard
* @return array{array{int, int, int}, array{int, int, int}} [lower, upper] bounds
*/
private static function wildcardBounds($value): array
{
if ($value === null || $value === "") {
throw new InconclusiveMatchException("Cannot parse empty or null value as semver wildcard");
}
$text = trim(strval($value));
// Strip v/V prefix
$text = ltrim($text, "vV");
// Split on dots
$parts = explode(".", $text);
// Remove trailing wildcard parts and empty parts
while (count($parts) > 0 && (end($parts) === "*" || end($parts) === "x" || end($parts) === "X" || end($parts) === "")) {
array_pop($parts);
}
if (count($parts) === 0) {
throw new InconclusiveMatchException("Cannot parse semver wildcard: no version components found in {$value}");
}
// Parse major
if (!preg_match('/^[0-9]+$/', $parts[0])) {
throw new InconclusiveMatchException("Cannot parse semver wildcard: invalid major version in {$value}");
}
$major = intval($parts[0]);
if (count($parts) === 1) {
// X.* pattern
$lower = [$major, 0, 0];
$upper = [$major + 1, 0, 0];
} else {
// X.Y.* pattern
if (!preg_match('/^[0-9]+$/', $parts[1])) {
throw new InconclusiveMatchException("Cannot parse semver wildcard: invalid minor version in {$value}");
}
$minor = intval($parts[1]);
$lower = [$major, $minor, 0];
$upper = [$major, $minor + 1, 0];
}
return [$lower, $upper];
}
private static function convertToDateTime($value)
{
if ($value instanceof \DateTime) {
return $value;
} elseif (is_string($value)) {
try {
$date = new \DateTime($value);
if (!is_nan($date->getTimestamp())) {
return $date;
}
} catch (Exception $e) {
throw new InconclusiveMatchException("{$value} is in an invalid date format");
}
} else {
throw new InconclusiveMatchException("The date provided {$value} must be a string or date object");
}
}
private static function computeExactMatch($value, $overrideValue)
{
if (is_array($value)) {
return in_array(strtolower(FeatureFlag::valueToString($overrideValue)), array_map('strtolower', array_map(fn($val) => FeatureFlag::valueToString($val), $value)));
}
return strtolower(FeatureFlag::valueToString($value)) == strtolower(FeatureFlag::valueToString($overrideValue));
}
private static function valueToString($value)
{
if (is_bool($value)) {
return $value ? "true" : "false";
} else {
return strval($value);
}
}
private static function compare($lhs, $rhs, $operator, $type = "string")
{
// If type is string, we use strcmp to compare the two strings
// If type is numeric, we use <=> to compare the two numbers
if ($type == "string") {
$comparison = strcmp($lhs, $rhs);
} else {
$comparison = $lhs <=> $rhs;
}
if ($operator == "gt") {
return $comparison > 0;
} elseif ($operator == "gte") {
return $comparison >= 0;
} elseif ($operator == "lt") {
return $comparison < 0;
} elseif ($operator == "lte") {
return $comparison <= 0;
}
throw new \Exception("Invalid operator: " . $operator);
}
private static function hash($key, $distinctId, $salt = "")
{
$hashKey = sprintf("%s.%s%s", $key, $distinctId, $salt);
$hashVal = base_convert(substr(sha1($hashKey), 0, 15), 16, 10);
return $hashVal / LONG_SCALE;
}
private static function getMatchingVariant($flag, $distinctId)
{
$variants = FeatureFlag::variantLookupTable($flag);
foreach ($variants as $variant) {
if (
FeatureFlag::hash($flag["key"], $distinctId, "variant") >= $variant["value_min"]
&& FeatureFlag::hash($flag["key"], $distinctId, "variant") < $variant["value_max"]
) {
return $variant["key"];
}
}
return null;
}
private static function variantLookupTable($featureFlag)
{
$lookupTable = [];
$valueMin = 0;
$multivariates = (($featureFlag['filters'] ?? [])['multivariate'] ?? [])['variants'] ?? [];
foreach ($multivariates as $variant) {
$valueMax = $valueMin + $variant["rollout_percentage"] / 100;
array_push($lookupTable, [
"value_min" => $valueMin,
"value_max" => $valueMax,
"key" => $variant["key"]
]);
$valueMin = $valueMax;
}
return $lookupTable;
}
public static function matchFeatureFlagProperties($flag, $distinctId, $properties, $cohorts = [], $flagsByKey = null, $evaluationCache = null)
{
$flagConditions = ($flag["filters"] ?? [])["groups"] ?? [];
$isInconclusive = false;
foreach ($flagConditions as $condition) {
try {
if (FeatureFlag::isConditionMatch($flag, $distinctId, $condition, $properties, $cohorts, $flagsByKey, $evaluationCache)) {
$variantOverride = $condition["variant"] ?? null;
$flagVariants = (($flag["filters"] ?? [])["multivariate"] ?? [])["variants"] ?? [];
$variantKeys = array_map(function ($variant) {
return $variant["key"];
}, $flagVariants);
if ($variantOverride && in_array($variantOverride, $variantKeys)) {
return $variantOverride;
} else {
return FeatureFlag::getMatchingVariant($flag, $distinctId) ?? true;
}
}
} catch (RequiresServerEvaluationException $e) {
// Immediately propagate - this condition requires server-side data
throw $e;
} catch (InconclusiveMatchException $e) {
// If this is a flag dependency error, preserve the original message
if (
strpos($e->getMessage(), "Cannot evaluate flag dependency") !== false ||
strpos($e->getMessage(), "Circular dependency detected") !== false
) {
throw $e;
}
$isInconclusive = true;
}
}
if ($isInconclusive) {
throw new InconclusiveMatchException("Can't determine if feature flag is enabled or not with given properties"); //phpcs:ignore
}
return false;
}
private static function isConditionMatch($featureFlag, $distinctId, $condition, $properties, $cohorts, $flagsByKey = null, $evaluationCache = null)
{
$rolloutPercentage = array_key_exists("rollout_percentage", $condition) ? $condition["rollout_percentage"] : null;
if (count($condition['properties'] ?? []) > 0) {
foreach ($condition['properties'] as $property) {
$matches = false;
$propertyType = $property['type'] ?? null;
if ($propertyType == 'cohort') {
$matches = FeatureFlag::matchCohort($property, $properties, $cohorts, $flagsByKey, $evaluationCache, $distinctId);
} elseif ($propertyType == 'flag') {
$matches = FeatureFlag::evaluateFlagDependency($property, $flagsByKey, $evaluationCache, $distinctId, $properties, $cohorts);
} else {
$matches = FeatureFlag::matchProperty($property, $properties);
}
if (!$matches) {
return false;
}
}
if (is_null($rolloutPercentage)) {
return true;
}
}
if (!is_null($rolloutPercentage) && FeatureFlag::hash($featureFlag["key"], $distinctId) > ($rolloutPercentage / 100)) { //phpcs:ignore
return false;
}
return true;
}
private static function isRegularExpression($string)
{
if ($string === null) {
return false;
}
set_error_handler(function () {
}, E_WARNING);
$isRegularExpression = preg_match($string, "") !== false;
restore_error_handler();
return $isRegularExpression;
}
private static function prepareValueForRegex($value)
{
$regex = $value;
// If delimiter already exists, do nothing
if (FeatureFlag::isRegularExpression($regex)) {
return $regex;
}
if (substr($regex, 0, 1) != "/") {
$regex = "/" . $regex;
}
if (substr($regex, -1) != "/") {
$regex = $regex . "/";
}
return $regex;
}
public static function evaluateFlagDependency($property, $flagsByKey, $evaluationCache, $distinctId, $properties, $cohortProperties)
{
if ($flagsByKey === null || $evaluationCache === null) {
throw new InconclusiveMatchException(sprintf(
"Cannot evaluate flag dependency on '%s' without flags_by_key and evaluation_cache",
$property["key"] ?? "unknown"
));
}
// Check if dependency_chain is present - it should always be provided for flag dependencies
if (!array_key_exists("dependency_chain", $property)) {
throw new InconclusiveMatchException(sprintf(
"Cannot evaluate flag dependency on '%s' without dependency_chain",
$property["key"] ?? "unknown"
));
}
$dependencyChain = $property["dependency_chain"];
// Handle circular dependency (empty chain means circular)
if (count($dependencyChain) === 0) {
throw new InconclusiveMatchException(sprintf(
"Circular dependency detected for flag '%s'",
$property["key"] ?? "unknown"
));
}
// The flag key to evaluate is in the "key" field
$depFlagKey = $property["key"] ?? null;
if (!$depFlagKey) {
throw new InconclusiveMatchException(sprintf(
"Flag dependency missing 'key' field: %s",
json_encode($property)
));
}
// Check if we've already evaluated this flag
if (!array_key_exists($depFlagKey, $evaluationCache)) {
// Need to evaluate this dependency first
$depFlag = $flagsByKey[$depFlagKey] ?? null;
if (!$depFlag) {
// Missing flag dependency - cannot evaluate locally
$evaluationCache[$depFlagKey] = null;
throw new InconclusiveMatchException(sprintf(
"Cannot evaluate flag dependency '%s' - flag not found in local flags",
$depFlagKey
));
} else {
// Check if the flag is active (same check as in Client::computeFlagLocally)
if (!($depFlag["active"] ?? false)) {
$evaluationCache[$depFlagKey] = false;
} else {
// Recursively evaluate the dependency
try {
$depResult = FeatureFlag::matchFeatureFlagProperties(
$depFlag,
$distinctId,
$properties,
$cohortProperties,
$flagsByKey,
$evaluationCache
);
$evaluationCache[$depFlagKey] = $depResult;
} catch (InconclusiveMatchException $e) {
// If we can't evaluate a dependency, store null and propagate the error
$evaluationCache[$depFlagKey] = null;
throw new InconclusiveMatchException(sprintf(
"Cannot evaluate flag dependency '%s': %s",
$depFlagKey,
$e->getMessage()
));
}
}
}
}
// Get the evaluated flag value
$flagValue = $evaluationCache[$depFlagKey];
if ($flagValue === null) {
// Previously inconclusive - raise error again
throw new InconclusiveMatchException(sprintf(
"Flag dependency '%s' was previously inconclusive",
$depFlagKey
));
}
// Now check if the flag value matches the expected value in the property
$expectedValue = $property["value"] ?? null;
$operator = $property["operator"] ?? "exact";
if ($expectedValue !== null) {
// For flag dependencies, we need to compare the actual flag result with expected value
// using the flag_evaluates_to operator logic
if ($operator === "flag_evaluates_to") {
return FeatureFlag::matchesDependencyValue($expectedValue, $flagValue);
} else {
// This should never happen, but just to be defensive
throw new InconclusiveMatchException(sprintf(
"Flag dependency property for '%s' has invalid operator '%s'",
$depFlagKey,
$operator
));
}
}
// If no value check needed, return true (all dependencies passed)
return true;
}
public static function matchesDependencyValue($expectedValue, $actualValue)
{
// String variant case - check for exact match or boolean true
if (is_string($actualValue) && strlen($actualValue) > 0) {
if (is_bool($expectedValue)) {
// Any variant matches boolean true
return $expectedValue;
} elseif (is_string($expectedValue)) {
// variants are case-sensitive, hence our comparison is too
return $actualValue === $expectedValue;
} else {
return false;
}
}
// Boolean case - must match expected boolean value
elseif (is_bool($actualValue) && is_bool($expectedValue)) {
return $actualValue === $expectedValue;
}
// Default case
return false;
}
}