-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathOptimizely.php
1016 lines (923 loc) · 35 KB
/
Optimizely.php
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
/**
* Copyright 2016-2020, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Optimizely;
use Exception;
use Optimizely\Config\DatafileProjectConfig;
use Optimizely\Entity\Variation;
use Optimizely\Exceptions\InvalidAttributeException;
use Optimizely\Exceptions\InvalidEventTagException;
use Throwable;
use Monolog\Logger;
use Optimizely\DecisionService\DecisionService;
use Optimizely\DecisionService\FeatureDecision;
use Optimizely\Entity\Experiment;
use Optimizely\Entity\FeatureVariable;
use Optimizely\Enums\DecisionNotificationTypes;
use Optimizely\ErrorHandler\ErrorHandlerInterface;
use Optimizely\ErrorHandler\NoOpErrorHandler;
use Optimizely\Event\Builder\EventBuilder;
use Optimizely\Event\Dispatcher\DefaultEventDispatcher;
use Optimizely\Event\Dispatcher\EventDispatcherInterface;
use Optimizely\Logger\LoggerInterface;
use Optimizely\Logger\NoOpLogger;
use Optimizely\Notification\NotificationCenter;
use Optimizely\Notification\NotificationType;
use Optimizely\OptimizelyConfig\OptimizelyConfigService;
use Optimizely\ProjectConfigManager\HTTPProjectConfigManager;
use Optimizely\ProjectConfigManager\ProjectConfigManagerInterface;
use Optimizely\ProjectConfigManager\StaticProjectConfigManager;
use Optimizely\UserProfile\UserProfileServiceInterface;
use Optimizely\Utils\Errors;
use Optimizely\Utils\Validator;
use Optimizely\Utils\VariableTypeUtils;
/**
* Class Optimizely
*
* @package Optimizely
*/
class Optimizely
{
const EVENT_KEY = 'Event Key';
const EXPERIMENT_KEY = 'Experiment Key';
const FEATURE_FLAG_KEY = 'Feature Flag Key';
const USER_ID = 'User ID';
const VARIABLE_KEY = 'Variable Key';
const VARIATION_KEY = 'Variation Key';
/**
* @var DatafileProjectConfig
*/
private $_config;
/**
* @var DecisionService
*/
private $_decisionService;
/**
* @var ErrorHandlerInterface
*/
private $_errorHandler;
/**
* @var EventDispatcherInterface
*/
private $_eventDispatcher;
/**
* @var EventBuilder
*/
private $_eventBuilder;
/**
* @var boolean Denotes whether Optimizely object is valid or not.
*/
private $_isValid;
/**
* @var LoggerInterface
*/
private $_logger;
/**
* @var ProjectConfigManagerInterface
*/
public $configManager;
/**
* @var NotificationCenter
*/
public $notificationCenter;
/**
* Optimizely constructor for managing Full Stack PHP projects.
*
* @param $datafile string JSON string representing the project.
* @param $eventDispatcher EventDispatcherInterface
* @param $logger LoggerInterface
* @param $errorHandler ErrorHandlerInterface
* @param $skipJsonValidation boolean representing whether JSON schema validation needs to be performed.
* @param $userProfileService UserProfileServiceInterface
* @param $configManager ProjectConfigManagerInterface provides ProjectConfig through getConfig method.
* @param $notificationCenter NotificationCenter
* @param $sdkKey string uniquely identifying the datafile corresponding to project and environment combination. Must provide at least one of datafile or sdkKey.
*/
public function __construct(
$datafile,
EventDispatcherInterface $eventDispatcher = null,
LoggerInterface $logger = null,
ErrorHandlerInterface $errorHandler = null,
$skipJsonValidation = false,
UserProfileServiceInterface $userProfileService = null,
ProjectConfigManagerInterface $configManager = null,
NotificationCenter $notificationCenter = null,
$sdkKey = null
) {
$this->_isValid = true;
$this->_eventDispatcher = $eventDispatcher ?: new DefaultEventDispatcher();
$this->_logger = $logger ?: new NoOpLogger();
$this->_errorHandler = $errorHandler ?: new NoOpErrorHandler();
$this->_eventBuilder = new EventBuilder($this->_logger);
$this->_decisionService = new DecisionService($this->_logger, $userProfileService);
$this->notificationCenter = $notificationCenter ?: new NotificationCenter($this->_logger, $this->_errorHandler);
$this->configManager = $configManager;
if ($this->configManager === null) {
if ($sdkKey) {
$this->configManager = new HTTPProjectConfigManager($sdkKey, null, null, true, $datafile, $skipJsonValidation, $this->_logger, $this->_errorHandler, $this->notificationCenter);
} else {
$this->configManager = new StaticProjectConfigManager($datafile, $skipJsonValidation, $this->_logger, $this->_errorHandler);
}
}
}
/**
* Returns DatafileProjectConfig instance.
* @return DatafileProjectConfig DatafileProjectConfig instance or null
*/
protected function getConfig()
{
$config = $this->configManager->getConfig();
return $config instanceof DatafileProjectConfig ? $config : null;
}
/**
* Helper function to validate user inputs into the API methods.
*
* @param $attributes array Associative array of user attributes
* @param $eventTags array Hash representing metadata associated with an event.
*
* @return boolean Representing whether all user inputs are valid.
*/
private function validateUserInputs($attributes, $eventTags = null)
{
if (!is_null($attributes) && !Validator::areAttributesValid($attributes)) {
$this->_logger->log(Logger::ERROR, 'Provided attributes are in an invalid format.');
$this->_errorHandler->handleError(
new InvalidAttributeException('Provided attributes are in an invalid format.')
);
return false;
}
if (!is_null($eventTags)) {
if (!Validator::areEventTagsValid($eventTags)) {
$this->_logger->log(Logger::ERROR, 'Provided event tags are in an invalid format.');
$this->_errorHandler->handleError(
new InvalidEventTagException('Provided event tags are in an invalid format.')
);
return false;
}
}
return true;
}
/**
* @param string Experiment key
* @param string Variation key
* @param string User ID
* @param array Associative array of user attributes
* @param DatafileProjectConfig DatafileProjectConfig instance
*/
protected function sendImpressionEvent($config, $experimentKey, $variationKey, $flagKey, $ruleKey, $ruleType, $userId, $attributes)
{
$impressionEvent = $this->_eventBuilder
->createImpressionEvent($config, $experimentKey, $variationKey, $flagKey, $ruleKey, $ruleType, $userId, $attributes);
$this->_logger->log(Logger::INFO, sprintf('Activating user "%s" in experiment "%s".', $userId, $experimentKey));
$this->_logger->log(
Logger::DEBUG,
sprintf(
'Dispatching impression event to URL %s with params %s.',
$impressionEvent->getUrl(),
json_encode($impressionEvent->getParams())
)
);
try {
$this->_eventDispatcher->dispatchEvent($impressionEvent);
} catch (Throwable $exception) {
$this->_logger->log(
Logger::ERROR,
sprintf(
'Unable to dispatch impression event. Error %s',
$exception->getMessage()
)
);
} catch (Exception $exception) {
$this->_logger->log(
Logger::ERROR,
sprintf(
'Unable to dispatch impression event. Error %s',
$exception->getMessage()
)
);
}
$this->notificationCenter->sendNotifications(
NotificationType::ACTIVATE,
array(
$config->getExperimentFromKey($experimentKey),
$userId,
$attributes,
$config->getVariationFromKey($experimentKey, $variationKey),
$impressionEvent
)
);
}
/**
* Buckets visitor and sends impression event to Optimizely.
*
* @param $experimentKey string Key identifying the experiment.
* @param $userId string ID for user.
* @param $attributes array Attributes of the user.
*
* @return null|string Representing the variation key.
*/
public function activate($experimentKey, $userId, $attributes = null)
{
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return null;
}
if (!$this->validateInputs(
[
self::EXPERIMENT_KEY =>$experimentKey,
self::USER_ID => $userId
]
)
) {
return null;
}
$variationKey = $this->getVariation($experimentKey, $userId, $attributes);
if (is_null($variationKey)) {
$this->_logger->log(Logger::INFO, sprintf('Not activating user "%s".', $userId));
return null;
}
$this->sendImpressionEvent($config, $experimentKey, $variationKey, '', $experimentKey, FeatureDecision::DECITION_SOURCE_EXPERIMENT, $userId, $attributes);
return $variationKey;
}
/**
* Gets OptimizelyConfig object for the current ProjectConfig.
*
* @return OptimizelyConfig Representing current ProjectConfig.
*/
public function getOptimizelyConfig()
{
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return null;
}
$optConfigService = new OptimizelyConfigService($config);
return $optConfigService->getConfig();
}
/**
* Send conversion event to Optimizely.
*
* @param $eventKey string Event key representing the event which needs to be recorded.
* @param $userId string ID for user.
* @param $attributes array Attributes of the user.
* @param $eventTags array Hash representing metadata associated with the event.
*/
public function track($eventKey, $userId, $attributes = null, $eventTags = null)
{
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return;
}
if (!$this->validateInputs(
[
self::EVENT_KEY =>$eventKey,
self::USER_ID => $userId
]
)
) {
return null;
}
if (!$this->validateUserInputs($attributes, $eventTags)) {
return;
}
$event = $config->getEvent($eventKey);
if (is_null($event->getKey())) {
$this->_logger->log(Logger::INFO, sprintf('Not tracking user "%s" for event "%s".', $userId, $eventKey));
return;
}
$conversionEvent = $this->_eventBuilder
->createConversionEvent(
$config,
$eventKey,
$userId,
$attributes,
$eventTags
);
$this->_logger->log(Logger::INFO, sprintf('Tracking event "%s" for user "%s".', $eventKey, $userId));
$this->_logger->log(
Logger::DEBUG,
sprintf(
'Dispatching conversion event to URL %s with params %s.',
$conversionEvent->getUrl(),
json_encode($conversionEvent->getParams())
)
);
try {
$this->_eventDispatcher->dispatchEvent($conversionEvent);
} catch (Throwable $exception) {
$this->_logger->log(
Logger::ERROR,
sprintf(
'Unable to dispatch conversion event. Error %s',
$exception->getMessage()
)
);
} catch (Exception $exception) {
$this->_logger->log(
Logger::ERROR,
sprintf(
'Unable to dispatch conversion event. Error %s',
$exception->getMessage()
)
);
}
$this->notificationCenter->sendNotifications(
NotificationType::TRACK,
array(
$eventKey,
$userId,
$attributes,
$eventTags,
$conversionEvent
)
);
}
/**
* Get variation where user will be bucketed.
*
* @param $experimentKey string Key identifying the experiment.
* @param $userId string ID for user.
* @param $attributes array Attributes of the user.
*
* @return null|string Representing the variation key.
*/
public function getVariation($experimentKey, $userId, $attributes = null)
{
// TODO: Config should be passed as param when this is called from activate but
// since PHP is single-threaded we can leave this for now.
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return null;
}
if (!$this->validateInputs(
[
self::EXPERIMENT_KEY =>$experimentKey,
self::USER_ID => $userId
]
)
) {
return null;
}
$experiment = $config->getExperimentFromKey($experimentKey);
if (is_null($experiment->getKey())) {
return null;
}
if (!$this->validateUserInputs($attributes)) {
return null;
}
$variation = $this->_decisionService->getVariation($config, $experiment, $userId, $attributes);
$variationKey = ($variation === null) ? null : $variation->getKey();
if ($config->isFeatureExperiment($experiment->getId())) {
$decisionNotificationType = DecisionNotificationTypes::FEATURE_TEST;
} else {
$decisionNotificationType = DecisionNotificationTypes::AB_TEST;
}
$attributes = $attributes ?: [];
$this->notificationCenter->sendNotifications(
NotificationType::DECISION,
array(
$decisionNotificationType,
$userId,
$attributes,
(object) array(
'experimentKey'=> $experiment->getKey(),
'variationKey'=> $variationKey
)
)
);
return $variationKey;
}
/**
* Force a user into a variation for a given experiment.
*
* @param $experimentKey string Key identifying the experiment.
* @param $userId string The user ID to be used for bucketing.
* @param $variationKey string The variation key specifies the variation which the user
* will be forced into. If null, then clear the existing experiment-to-variation mapping.
*
* @return boolean A boolean value that indicates if the set completed successfully.
*/
public function setForcedVariation($experimentKey, $userId, $variationKey)
{
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return false;
}
if (!$this->validateInputs(
[
self::EXPERIMENT_KEY =>$experimentKey,
self::USER_ID => $userId
]
)) {
return false;
}
return $this->_decisionService->setForcedVariation($config, $experimentKey, $userId, $variationKey);
}
/**
* Gets the forced variation for a given user and experiment.
*
* @param $experimentKey string Key identifying the experiment.
* @param $userId string The user ID to be used for bucketing.
*
* @return string|null The forced variation key.
*/
public function getForcedVariation($experimentKey, $userId)
{
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return null;
}
if (!$this->validateInputs(
[
self::EXPERIMENT_KEY =>$experimentKey,
self::USER_ID => $userId
]
)) {
return null;
}
$forcedVariation = $this->_decisionService->getForcedVariation($config, $experimentKey, $userId);
if (isset($forcedVariation)) {
return $forcedVariation->getKey();
} else {
return null;
}
}
/**
* Determine whether a feature is enabled.
* Sends an impression event if the user is bucketed into an experiment using the feature.
*
* @param string Feature flag key
* @param string User ID
* @param array Associative array of user attributes
*
* @return boolean
*/
public function isFeatureEnabled($featureFlagKey, $userId, $attributes = null)
{
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return false;
}
if (!$this->validateInputs(
[
self::FEATURE_FLAG_KEY =>$featureFlagKey,
self::USER_ID => $userId
]
)
) {
return false;
}
$featureFlag = $config->getFeatureFlagFromKey($featureFlagKey);
if ($featureFlag && (!$featureFlag->getId())) {
// Error logged in DatafileProjectConfig - getFeatureFlagFromKey
return false;
}
//validate feature flag
if (!Validator::isFeatureFlagValid($config, $featureFlag)) {
return false;
}
$featureEnabled = false;
$decision = $this->_decisionService->getVariationForFeature($config, $featureFlag, $userId, $attributes);
$variation = $decision->getVariation();
if ($config->getSendFlagDecisions() && ($decision->getSource() == FeatureDecision::DECISION_SOURCE_ROLLOUT || !$variation)) {
$ruleKey = $decision->getExperiment() ? $decision->getExperiment()->getKey() : '';
$this->sendImpressionEvent($config, $ruleKey, $variation ? $variation->getKey() : '', $featureFlagKey, $ruleKey, $decision->getSource(), $userId, $attributes);
}
if ($variation) {
$experimentKey = $decision->getExperiment()->getKey();
$featureEnabled = $variation->getFeatureEnabled();
if ($decision->getSource() == FeatureDecision::DECISION_SOURCE_FEATURE_TEST) {
$sourceInfo = (object) array(
'experimentKey'=> $experimentKey,
'variationKey'=> $variation->getKey()
);
$this->sendImpressionEvent($config, $experimentKey, $variation->getKey(), $featureFlagKey, $experimentKey, $decision->getSource(), $userId, $attributes);
} else {
$this->_logger->log(Logger::INFO, "The user '{$userId}' is not being experimented on Feature Flag '{$featureFlagKey}'.");
}
}
$attributes = is_null($attributes) ? [] : $attributes;
$this->notificationCenter->sendNotifications(
NotificationType::DECISION,
array(
DecisionNotificationTypes::FEATURE,
$userId,
$attributes,
(object) array(
'featureKey'=>$featureFlagKey,
'featureEnabled'=> $featureEnabled,
'source'=> $decision->getSource(),
'sourceInfo'=> isset($sourceInfo) ? $sourceInfo : (object) array()
)
)
);
if ($featureEnabled == true) {
$this->_logger->log(Logger::INFO, "Feature Flag '{$featureFlagKey}' is enabled for user '{$userId}'.");
return $featureEnabled;
}
$this->_logger->log(Logger::INFO, "Feature Flag '{$featureFlagKey}' is not enabled for user '{$userId}'.");
return false;
}
/**
* Get keys of all feature flags which are enabled for the user
*
* @param string User ID
* @param array Associative array of user attributes
* @return array List of feature flag keys
*/
public function getEnabledFeatures($userId, $attributes = null)
{
$enabledFeatureKeys = [];
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return $enabledFeatureKeys;
}
if (!$this->validateInputs(
[
self::USER_ID => $userId
]
)
) {
return $enabledFeatureKeys;
}
$featureFlags = $config->getFeatureFlags();
foreach ($featureFlags as $feature) {
$featureKey = $feature->getKey();
if ($this->isFeatureEnabled($featureKey, $userId, $attributes) === true) {
$enabledFeatureKeys[] = $featureKey;
}
}
return $enabledFeatureKeys;
}
/**
* Get value of the specified variable in the feature flag.
*
* @param string Feature flag key
* @param string Variable key
* @param string User ID
* @param array Associative array of user attributes
* @param string Variable type
*
* @return string|boolean|number|array|null Value of the variable cast to the appropriate
* type, or null if the feature key is invalid, the
* variable key is invalid, or there is a mismatch
* with the type of the variable
*/
public function getFeatureVariableValueForType(
$featureFlagKey,
$variableKey,
$userId,
$attributes = null,
$variableType = null
) {
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, FeatureVariable::getFeatureVariableMethodName($variableType)));
return null;
}
if (!$this->validateInputs(
[
self::FEATURE_FLAG_KEY => $featureFlagKey,
self::VARIABLE_KEY => $variableKey,
self::USER_ID => $userId
]
)
) {
return null;
}
$featureFlag = $config->getFeatureFlagFromKey($featureFlagKey);
if ($featureFlag && (!$featureFlag->getId())) {
// Error logged in DatafileProjectConfig - getFeatureFlagFromKey
return null;
}
$decision = $this->_decisionService->getVariationForFeature($config, $featureFlag, $userId, $attributes);
$variation = $decision->getVariation();
$experiment = $decision->getExperiment();
$featureEnabled = $variation !== null ? $variation->getFeatureEnabled() : false;
$variableValue = $this->getFeatureVariableValueFromVariation($featureFlagKey, $variableKey, $variableType, $featureEnabled, $variation, $userId);
// returning as variable not found or type is invalid
if ($variableValue === null) {
return null;
}
if ($variation && $decision->getSource() == FeatureDecision::DECISION_SOURCE_FEATURE_TEST) {
$sourceInfo = (object) array(
'experimentKey'=> $experiment->getKey(),
'variationKey'=> $variation->getKey()
);
}
$attributes = $attributes ?: [];
$this->notificationCenter->sendNotifications(
NotificationType::DECISION,
array(
DecisionNotificationTypes::FEATURE_VARIABLE,
$userId,
$attributes,
(object) array(
'featureKey'=>$featureFlagKey,
'featureEnabled'=> $featureEnabled,
'variableKey'=> $variableKey,
'variableType'=> $variableType,
'variableValue'=> $variableValue,
'source'=> $decision->getSource(),
'sourceInfo'=> isset($sourceInfo) ? $sourceInfo : (object) array()
)
)
);
return $variableValue;
}
/**
* Get the Boolean value of the specified variable in the feature flag.
*
* @param string Feature flag key
* @param string Variable key
* @param string User ID
* @param array Associative array of user attributes
*
* @return string boolean variable value / null
*/
public function getFeatureVariableBoolean($featureFlagKey, $variableKey, $userId, $attributes = null)
{
return $this->getFeatureVariableValueForType(
$featureFlagKey,
$variableKey,
$userId,
$attributes,
FeatureVariable::BOOLEAN_TYPE
);
}
/**
* Get the Integer value of the specified variable in the feature flag.
*
* @param string Feature flag key
* @param string Variable key
* @param string User ID
* @param array Associative array of user attributes
*
* @return string integer variable value / null
*/
public function getFeatureVariableInteger($featureFlagKey, $variableKey, $userId, $attributes = null)
{
return $this->getFeatureVariableValueForType(
$featureFlagKey,
$variableKey,
$userId,
$attributes,
FeatureVariable::INTEGER_TYPE
);
}
/**
* Get the Double value of the specified variable in the feature flag.
*
* @param string Feature flag key
* @param string Variable key
* @param string User ID
* @param array Associative array of user attributes
*
* @return string double variable value / null
*/
public function getFeatureVariableDouble($featureFlagKey, $variableKey, $userId, $attributes = null)
{
return $this->getFeatureVariableValueForType(
$featureFlagKey,
$variableKey,
$userId,
$attributes,
FeatureVariable::DOUBLE_TYPE
);
}
/**
* Get the String value of the specified variable in the feature flag.
*
* @param string Feature flag key
* @param string Variable key
* @param string User ID
* @param array Associative array of user attributes
*
* @return string variable value / null
*/
public function getFeatureVariableString($featureFlagKey, $variableKey, $userId, $attributes = null)
{
return $this->getFeatureVariableValueForType(
$featureFlagKey,
$variableKey,
$userId,
$attributes,
FeatureVariable::STRING_TYPE
);
}
/**
* Get the JSON value of the specified variable in the feature flag.
*
* @param string Feature flag key
* @param string Variable key
* @param string User ID
* @param array Associative array of user attributes
*
* @return array Associative array of json variable including key and value
*/
public function getFeatureVariableJSON($featureFlagKey, $variableKey, $userId, $attributes = null)
{
return $this->getFeatureVariableValueForType(
$featureFlagKey,
$variableKey,
$userId,
$attributes,
FeatureVariable::JSON_TYPE
);
}
/**
* Returns values for all the variables attached to the given feature
*
* @param string Feature flag key
* @param string User ID
* @param array Associative array of user attributes
*
* @return array|null array of all the variables, or null if the feature key is invalid
*/
public function getAllFeatureVariables($featureFlagKey, $userId, $attributes = null)
{
$config = $this->getConfig();
if ($config === null) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_DATAFILE, __FUNCTION__));
return null;
}
if (!$this->validateInputs(
[
self::FEATURE_FLAG_KEY => $featureFlagKey,
self::USER_ID => $userId
]
)
) {
return null;
}
$featureFlag = $config->getFeatureFlagFromKey($featureFlagKey);
if ($featureFlag && (!$featureFlag->getId())) {
return null;
}
$decision = $this->_decisionService->getVariationForFeature($config, $featureFlag, $userId, $attributes);
$variation = $decision->getVariation();
$experiment = $decision->getExperiment();
$featureEnabled = $variation !== null ? $variation->getFeatureEnabled() : false;
$allVariables = [];
foreach ($featureFlag->getVariables() as $variable) {
$allVariables[$variable->getKey()] = $this->getFeatureVariableValueFromVariation(
$featureFlagKey,
$variable->getKey(),
null,
$featureEnabled,
$variation,
$userId
);
}
$sourceInfo = (object) array();
if ($variation && $decision->getSource() == FeatureDecision::DECISION_SOURCE_FEATURE_TEST) {
$sourceInfo = (object) array(
'experimentKey'=> $experiment->getKey(),
'variationKey'=> $variation->getKey()
);
}
$attributes = $attributes ?: [];
$this->notificationCenter->sendNotifications(
NotificationType::DECISION,
array(
DecisionNotificationTypes::ALL_FEATURE_VARIABLES,
$userId,
$attributes,
(object)array(
'featureKey' => $featureFlagKey,
'featureEnabled' => $featureEnabled,
'variableValues' => $allVariables,
'source' => $decision->getSource(),
'sourceInfo' => $sourceInfo
)
)
);
return $allVariables;
}
/**
* Get the value of the specified variable on the basis of its status and usage
*
* @param string Feature flag key
* @param string Variable key
* @param boolean Feature Status
* @param Variation for feature
* @param string User Id
*
* @return string|boolean|number|array|null Value of the variable cast to the appropriate
* type, or null if the feature key is invalid, the
* variable key is invalid, or there is a mismatch
* with the type of the variable
*/
private function getFeatureVariableValueFromVariation($featureFlagKey, $variableKey, $variableType, $featureEnabled, $variation, $userId)
{
$config = $this->getConfig();
$variable = $config->getFeatureVariableFromKey($featureFlagKey, $variableKey);
if (!$variable) {
// Error message logged in ProjectConfigInterface- getFeatureVariableFromKey
return null;
}
if ($variableType && $variableType != $variable->getType()) {
$this->_logger->log(
Logger::ERROR,
"Variable is of type '{$variable->getType()}', but you requested it as type '{$variableType}'."
);
return null;
}
$variableValue = $variable->getDefaultValue();
if ($variation === null) {
$this->_logger->log(
Logger::INFO,
"User '{$userId}' is not in experiment or rollout, ".
"returning default value '{$variableValue}'."
);
} else {
if ($featureEnabled) {
$variableUsage = $variation->getVariableUsageById($variable->getId());
if ($variableUsage) {
$variableValue = $variableUsage->getValue();
$this->_logger->log(
Logger::INFO,
"Returning variable value '{$variableValue}' for variable key '{$variableKey}' ".
"of feature flag '{$featureFlagKey}'."
);
} else {
$this->_logger->log(
Logger::INFO,
"Variable value is not defined. Returning the default variable value '{$variableValue}'."
);
}
} else {
$this->_logger->log(
Logger::INFO,
"Feature '{$featureFlagKey}' is not enabled for user '{$userId}'. ".
"Returning the default variable value '{$variableValue}'."
);
}
}
if (!is_null($variableValue)) {
$variableValue = VariableTypeUtils::castStringToType($variableValue, $variable->getType(), $this->_logger);
}
return $variableValue;
}
/**
* Determine if the instance of the Optimizely client is valid.
* An instance can be deemed invalid if it was not initialized
* properly due to an invalid datafile being passed in.
*
* @return True if the Optimizely instance is valid.
* False if the Optimizely instance is not valid.
*/
public function isValid()
{
return $this->getConfig() !== null;
}
/**
* Calls Validator::validateNonEmptyString for each value in array
* Logs for each invalid value
*
* @param array values to validate
* @param logger
*
* @return bool True if all of the values are valid, False otherwise
*/
protected function validateInputs(array $values, $logLevel = Logger::ERROR)
{
$isValid = true;
if (array_key_exists(self::USER_ID, $values)) {
// Empty str is a valid user ID
if (!is_string($values[self::USER_ID])) {
$this->_logger->log(Logger::ERROR, sprintf(Errors::INVALID_FORMAT, self::USER_ID));