-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathValidator.php
306 lines (264 loc) · 9.79 KB
/
Validator.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
<?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\Utils;
use JsonSchema;
use Monolog\Logger;
use Optimizely\Config\ProjectConfigInterface;
use Optimizely\Entity\Experiment;
use Optimizely\Enums\ExperimentAudienceEvaluationLogs;
use Optimizely\Enums\RolloutAudienceEvaluationLogs;
use Optimizely\Logger\LoggerInterface;
use Optimizely\Utils\ConditionTreeEvaluator;
use Optimizely\Utils\CustomAttributeConditionEvaluator;
class Validator
{
/**
* @param $datafile string JSON string representing the project.
*
* @return boolean Representing whether schema is valid or not.
*/
public static function validateJsonSchema($datafile, LoggerInterface $logger = null)
{
$data = json_decode($datafile);
// Validate
$validator = new JsonSchema\Validator;
$validator->check($data, (object)['$ref' => 'file://' . __DIR__.'/schema.json']);
if ($validator->isValid()) {
return true;
} else {
if ($logger) {
$logger->log(Logger::DEBUG, "JSON does not validate. Violations:\n");
;
foreach ($validator->getErrors() as $error) {
$logger->log(Logger::DEBUG, "[%s] %s\n", $error['property'], $error['message']);
}
}
return false;
}
}
/**
* @param $attributes mixed Attributes of the user.
*
* @return boolean Representing whether attributes are valid or not.
*/
public static function areAttributesValid($attributes)
{
if (!is_array($attributes)) {
return false;
}
if (empty($attributes)) {
return true;
}
// At least one key string to be an associative array.
return count(array_filter(array_keys($attributes), 'is_string')) > 0;
}
/**
* @param $value The value to validate.
*
* @return boolean Representing whether attribute's value is
* a number and not NAN, INF, -INF or greater than absolute limit of 2^53.
*/
public static function isFiniteNumber($value)
{
if (!(is_int($value) || is_float($value))) {
return false;
}
if (is_nan($value) || is_infinite($value)) {
return false;
}
if (abs($value) > pow(2, 53)) {
return false;
}
return true;
}
/**
* @param $attributeKey The key to validate.
* @param $attributeValue The value to validate.
*
* @return boolean Representing whether attribute's key and value are
* valid for event payload or not. Valid attribute key must be a string.
* Valid attribute value can be a string, bool, or a finite number.
*/
public static function isAttributeValid($attributeKey, $attributeValue)
{
if (!is_string($attributeKey)) {
return false;
}
if (is_string($attributeValue) || is_bool($attributeValue)) {
return true;
}
if (is_int($attributeValue) || is_float($attributeValue)) {
return Validator::isFiniteNumber($attributeValue);
}
return false;
}
/**
* @param $eventTags mixed Event tags to be validated.
*
* @return boolean Representing whether event tags are valid or not.
*/
public static function areEventTagsValid($eventTags)
{
return is_array($eventTags) && count(array_filter(array_keys($eventTags), 'is_int')) == 0;
}
/**
* @param $config ProjectConfigInterface Configuration for the project.
* @param $experiment Experiment Entity representing the experiment.
* @param $userAttributes array Attributes of the user.
* @param $logger LoggerInterface.
* @param $isRollout Boolean true if experiment to evaluate is a rollout rule.
* @param $rolloutRule String Rollout rule identifier to log.
*
* @return boolean Representing whether user meets audience conditions to be in experiment or not.
*/
public static function doesUserMeetAudienceConditions($config, $experiment, $userAttributes, $logger, $isRollout = null, $rolloutRule = null)
{
$loggingClass = 'Optimizely\Enums\ExperimentAudienceEvaluationLogs';
$loggingStr = $experiment->getKey();
if ($isRollout) {
$loggingClass = 'Optimizely\Enums\RolloutAudienceEvaluationLogs';
$loggingStr = $rolloutRule;
}
$audienceConditions = $experiment->getAudienceConditions();
if ($audienceConditions === null) {
$audienceConditions = $experiment->getAudienceIds();
}
$logger->log(Logger::DEBUG, sprintf(
$loggingClass::EVALUATING_AUDIENCES_COMBINED,
$loggingStr,
json_encode($audienceConditions)
));
// Return true if experiment is not targeted to any audience.
if (empty($audienceConditions)) {
$logger->log(Logger::INFO, sprintf(
$loggingClass::AUDIENCE_EVALUATION_RESULT_COMBINED,
$loggingStr,
'TRUE'
));
return true;
}
if ($userAttributes === null) {
$userAttributes = [];
}
$customAttrCondEval = new CustomAttributeConditionEvaluator($userAttributes, $logger);
$evaluateCustomAttr = function ($leafCondition) use ($customAttrCondEval) {
return $customAttrCondEval->evaluate($leafCondition);
};
$evaluateAudience = function ($audienceId) use ($config, $evaluateCustomAttr, $logger, $loggingClass) {
$audience = $config->getAudience($audienceId);
if ($audience === null) {
return null;
}
$logger->log(Logger::DEBUG, sprintf(
$loggingClass::EVALUATING_AUDIENCE,
$audienceId,
json_encode($audience->getConditionsList())
));
$conditionTreeEvaluator = new ConditionTreeEvaluator();
$result = $conditionTreeEvaluator->evaluate($audience->getConditionsList(), $evaluateCustomAttr);
$resultStr = $result === null ? 'UNKNOWN' : strtoupper(var_export($result, true));
$logger->log(Logger::DEBUG, sprintf(
$loggingClass::AUDIENCE_EVALUATION_RESULT,
$audienceId,
$resultStr
));
return $result;
};
$conditionTreeEvaluator = new ConditionTreeEvaluator();
$evalResult = $conditionTreeEvaluator->evaluate($audienceConditions, $evaluateAudience);
$evalResult = $evalResult || false;
$logger->log(Logger::INFO, sprintf(
$loggingClass::AUDIENCE_EVALUATION_RESULT_COMBINED,
$loggingStr,
strtoupper(var_export($evalResult, true))
));
return $evalResult;
}
/**
* Checks that if there are more than one experiment IDs
* in the feature flag, they must belong to the same mutex group
*
* @param ProjectConfigInterface $config The project config to verify against
* @param FeatureFlag $featureFlag The feature to validate
*
* @return boolean True if feature flag is valid
*/
public static function isFeatureFlagValid($config, $featureFlag)
{
$experimentIds = $featureFlag->getExperimentIds();
if (empty($experimentIds)) {
return true;
}
if (sizeof($experimentIds) == 1) {
return true;
}
$groupId = $config->getExperimentFromId($experimentIds[0])->getGroupId();
foreach ($experimentIds as $id) {
$experiment = $config->getExperimentFromId($id);
$grpId = $experiment->getGroupId();
if ($groupId != $grpId) {
return false;
}
}
return true;
}
/**
* Checks if the provided value is a non-empty string
*
* @param $value The value to validate
*
* @return boolean True if $value is a non-empty string
*/
public static function validateNonEmptyString($value)
{
if (is_string($value) && $value!='') {
return true;
}
return false;
}
/**
* Method to verify that both values belong to same type.
* Float/Double and Integer are considered similar.
*
* @param mixed $firstVal
* @param mixed $secondVal
*
* @return bool True if values belong to similar types. Otherwise, False.
*/
public static function areValuesSameType($firstVal, $secondVal)
{
$firstValType = gettype($firstVal);
$secondValType = gettype($secondVal);
$numberTypes = array('double', 'integer');
if (in_array($firstValType, $numberTypes) && in_array($secondValType, $numberTypes)) {
return true;
}
return $firstValType == $secondValType;
}
/**
* Returns true only if given input is an array with all of it's keys of type string.
* @param mixed $arr
* @return bool True if array contains all string keys. Otherwise, false.
*/
public static function doesArrayContainOnlyStringKeys($arr)
{
if (!is_array($arr) || empty($arr)) {
return false;
}
return count(array_filter(array_keys($arr), 'is_string')) == count(array_keys($arr));
}
}