-
Notifications
You must be signed in to change notification settings - Fork 28
/
Optimizely.php
366 lines (323 loc) · 13 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
<?php
/**
* Copyright 2016-2017, 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\Exceptions\InvalidAttributeException;
use Optimizely\Exceptions\InvalidEventTagException;
use Throwable;
use Monolog\Logger;
use Optimizely\Entity\Experiment;
use Optimizely\Logger\DefaultLogger;
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\Utils\EventTagUtils;
use Optimizely\Utils\Validator;
/**
* Class Optimizely
*
* @package Optimizely
*/
class Optimizely
{
/**
* @var EventDispatcherInterface
*/
private $_eventDispatcher;
/**
* @var LoggerInterface
*/
private $_logger;
/**
* @var ErrorHandlerInterface
*/
private $_errorHandler;
/**
* @var ProjectConfig
*/
private $_config;
/**
* @var Bucketer
*/
private $_bucketer;
/**
* @var EventBuilder
*/
private $_eventBuilder;
/**
* @var boolean Denotes whether Optimizely object is valid or not.
*/
private $_isValid;
/**
* 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.
*/
public function __construct($datafile,
EventDispatcherInterface $eventDispatcher = null,
LoggerInterface $logger = null,
ErrorHandlerInterface $errorHandler = null,
$skipJsonValidation = false)
{
$this->_isValid = true;
$this->_eventDispatcher = $eventDispatcher ?: new DefaultEventDispatcher();
$this->_logger = $logger ?: new NoOpLogger();
$this->_errorHandler = $errorHandler ?: new NoOpErrorHandler();
if (!$this->validateInputs($datafile, $skipJsonValidation)) {
$this->_isValid = false;
$this->_logger = new DefaultLogger();
$this->_logger->log(Logger::ERROR, 'Provided "datafile" has invalid schema.');
return;
}
try {
$this->_config = new ProjectConfig($datafile, $this->_logger, $this->_errorHandler);
}
catch (Throwable $exception) {
$this->_isValid = false;
$this->_logger = new DefaultLogger();
$this->_logger->log(Logger::ERROR, 'Provided "datafile" is in an invalid format.');
return;
}
catch (Exception $exception) {
$this->_isValid = false;
$this->_logger = new DefaultLogger();
$this->_logger->log(Logger::ERROR, 'Provided "datafile" is in an invalid format.');
return;
}
$this->_bucketer = new Bucketer($this->_logger);
$this->_eventBuilder = new EventBuilder($this->_bucketer);
}
/**
* @param $datafile string JSON string representing the project.
* @param $skipJsonValidation boolean representing whether JSON schema validation needs to be performed.
*
* @return boolean Representing whether all provided inputs are valid or not.
*/
private function validateInputs($datafile, $skipJsonValidation)
{
if (!$skipJsonValidation && !Validator::validateJsonSchema($datafile)) {
return false;
}
return true;
}
/**
* Helper function to validate all required conditions before performing activate or track.
*
* @param $experiment Experiment Object representing experiment.
* @param $userId string ID for user.
* @param $attributes array User attributes.
* @return boolean Representing whether all conditions are met or not.
*/
private function validatePreconditions($experiment, $userId, $attributes)
{
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 (!$experiment->isExperimentRunning()) {
$this->_logger->log(Logger::INFO, sprintf('Experiment "%s" is not running.', $experiment->getKey()));
return false;
}
if ($experiment->isUserInForcedVariation($userId)) {
return true;
}
if (!Validator::isUserInExperiment($this->_config, $experiment, $attributes)) {
$this->_logger->log(
Logger::INFO,
sprintf('User "%s" does not meet conditions to be in experiment "%s".', $userId, $experiment->getKey())
);
return false;
}
return true;
}
/**
* 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 variation.
*/
public function activate($experimentKey, $userId, $attributes = null)
{
if (!$this->_isValid) {
$this->_logger->log(Logger::ERROR, 'Datafile has invalid format. Failing "activate".');
return null;
}
$experiment = $this->_config->getExperimentFromKey($experimentKey);
if (is_null($experiment->getKey())) {
$this->_logger->log(Logger::INFO, sprintf('Not activating user "%s".', $userId));
return null;
}
if (!$this->validatePreconditions($experiment, $userId, $attributes)) {
$this->_logger->log(Logger::INFO, sprintf('Not activating user "%s".', $userId));
return null;
}
$variation = $this->_bucketer->bucket($this->_config, $experiment, $userId);
$variationKey = $variation->getKey();
if (is_null($variationKey)) {
$this->_logger->log(Logger::INFO, sprintf('Not activating user "%s".', $userId));
return $variationKey;
}
$impressionEvent = $this->_eventBuilder
->createImpressionEvent($this->_config, $experiment, $variation->getId(), $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(), http_build_query($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()));
}
return $variationKey;
}
/**
* 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)
{
if (!$this->_isValid) {
$this->_logger->log(Logger::ERROR, 'Datafile has invalid format. Failing "track".');
return;
}
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;
}
if (!is_null($eventTags)) {
if (is_numeric($eventTags) && !is_string($eventTags)) {
$eventTags = array(
EventTagUtils::REVENUE_EVENT_METRIC_NAME => $eventTags,
);
$this->_logger->log(
Logger::WARNING,
'Event value is deprecated in track call. Use event tags to pass in revenue value instead.'
);
}
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.')
);
}
}
$event = $this->_config->getEvent($eventKey);
if (is_null($event->getKey())) {
$this->_logger->log(Logger::ERROR, sprintf('Not tracking user "%s" for event "%s".', $userId, $eventKey));
return;
}
// Filter out experiments that are not running or when user(s) do not meet conditions.
$validExperiments = [];
forEach ($event->getExperimentIds() as $experimentId) {
$experiment = $this->_config->getExperimentFromId($experimentId);
if ($this->validatePreconditions($experiment, $userId, $attributes)) {
array_push($validExperiments, $experiment);
} else {
$this->_logger->log(Logger::INFO, sprintf('Not tracking user "%s" for experiment "%s".',
$userId, $experiment->getKey()));
}
}
if (!empty($validExperiments)) {
$conversionEvent = $this->_eventBuilder
->createConversionEvent(
$this->_config,
$eventKey,
$validExperiments,
$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(), http_build_query($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()));
}
} else {
$this->_logger->log(
Logger::INFO,
sprintf('There are no valid experiments for event "%s" to track.', $eventKey)
);
}
}
/**
* 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 variation.
*/
public function getVariation($experimentKey, $userId, $attributes = null)
{
if (!$this->_isValid) {
$this->_logger->log(Logger::ERROR, 'Datafile has invalid format. Failing "getVariation".');
return null;
}
$experiment = $this->_config->getExperimentFromKey($experimentKey);
if (is_null($experiment->getKey())) {
return null;
}
if (!$this->validatePreconditions($experiment, $userId, $attributes)) {
return null;
}
$variation = $this->_bucketer->bucket($this->_config, $experiment, $userId);
return $variation->getKey();
}
}