-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathFlagsmith.php
More file actions
623 lines (560 loc) · 18.3 KB
/
Flagsmith.php
File metadata and controls
623 lines (560 loc) · 18.3 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
<?php
namespace Flagsmith;
use Flagsmith\Concerns\HasWith;
use Flagsmith\Engine\Engine;
use Flagsmith\Engine\Environments\EnvironmentModel;
use Flagsmith\Engine\Identities\IdentityModel;
use Flagsmith\Engine\Identities\Traits\TraitModel;
use Flagsmith\Engine\Segments\SegmentEvaluator;
use Flagsmith\Engine\Utils\Collections\FeatureStateModelList;
use Flagsmith\Engine\Utils\Collections\IdentityTraitList;
use Flagsmith\Exceptions\APIException;
use Flagsmith\Exceptions\FlagsmithAPIError;
use Flagsmith\Exceptions\FlagsmithClientError;
use Flagsmith\Exceptions\FlagsmithThrowable;
use Flagsmith\Models\Flags;
use Flagsmith\Models\Segment;
use Flagsmith\Utils\AnalyticsProcessor;
use Flagsmith\Utils\IdentitiesGenerator;
use Flagsmith\Utils\Retry;
use JsonException;
use ValueError;
use Psr\Http\Client\ClientInterface;
use Psr\SimpleCache\CacheInterface;
use Http\Discovery\Psr18ClientDiscovery;
use Http\Discovery\Psr17FactoryDiscovery;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
class Flagsmith
{
use HasWith;
public const DEFAULT_API_URL = 'https://edge.api.flagsmith.com/api/v1';
private string $apiKey;
private string $host = self::DEFAULT_API_URL;
private ?object $customHeaders = null;
private ?int $environmentTtl = null;
private Retry $retries;
private ?AnalyticsProcessor $analyticsProcessor = null;
private ?\Closure $defaultFlagHandler = null;
private ClientInterface $client;
private RequestFactoryInterface $requestFactory;
private StreamFactoryInterface $streamFactory;
private string $environment_flags_url = 'flags/';
private string $identities_url = 'identities/';
private string $environment_url = 'environment-document/';
private ?Cache $cache = null;
private ?int $timeToLive = null;
private string $cachePrefix = 'flagsmith';
private bool $skipCache = false;
private bool $useCacheAsFailover = false;
private array $headers = [];
private ?EnvironmentModel $environment = null;
/**
* @throws ValueError
*/
public function __construct(
string $apiKey,
string $host = self::DEFAULT_API_URL,
object $customHeaders = null,
int $environmentTtl = null,
Retry $retries = null,
bool $enableAnalytics = false,
\Closure $defaultFlagHandler = null
) {
$this->apiKey = $apiKey;
$this->host = rtrim($host, '/');
$this->customHeaders = $customHeaders ?? $this->customHeaders;
$this->environmentTtl = $environmentTtl ?? $this->environmentTtl;
$this->retries = $retries ?? new Retry(3);
$this->analyticsProcessor = $enableAnalytics ? new AnalyticsProcessor($apiKey, $host) : null;
$this->defaultFlagHandler = $defaultFlagHandler ?? $this->defaultFlagHandler;
if (is_int($environmentTtl)) {
if (stripos($this->apiKey, 'ser.') === false) {
throw new ValueError(
'In order to use local evaluation, please generate a server key in the environment settings page.'
);
}
}
//We default to using Guzzle for the HTTP client (as this is how it worked in 1.0)
$this->client = Psr18ClientDiscovery::find();
$this->requestFactory = Psr17FactoryDiscovery::findRequestFactory();
$this->streamFactory = Psr17FactoryDiscovery::findStreamFactory();
}
/**
* Build with customer headers.
* @param object $customHeaders
* @return Flagsmith
*/
public function withCustomHeaders(object $customHeaders): self
{
return $this->with('customHeaders', $customHeaders);
}
/**
* Build with Retry object.
* @param Retry $retries
* @return Flagsmith
*/
public function withRetries(Retry $retries): self
{
return $this->with('retries', $retries);
}
/**
* Build with Environment cache TTL.
* @param int $environmentTtl
* @return Flagsmith
*/
public function withEnvironmentTtl(int $environmentTtl): self
{
return $this->with('environmentTtl', $environmentTtl);
}
/**
* Build with enable Analytics.
* @param bool $enableAnalytics
* @return Flagsmith
*/
public function withAnalytics(AnalyticsProcessor $analytics): self
{
return $this->with('analyticsProcessor', $analytics);
}
/**
* Build with default flag handler.
* @param \Closure $defaultFlagHandler
* @return Flagsmith
*/
public function withDefaultFlagHandler(\Closure $defaultFlagHandler): self
{
return $this->with('defaultFlagHandler', $defaultFlagHandler);
}
/**
* Set the Client
*
* @param ClientInterface $client
* @return self
*/
public function withClient(ClientInterface $client): self
{
return $this->with('client', $client);
}
/**
* Set the Request Factory
*
* @param RequestFactoryInterface $requestFactory
* @return self
*/
public function withRequestFactory(
RequestFactoryInterface $requestFactory
): self {
return $this->with('requestFactory', $requestFactory);
}
/**
* Set the Stream Factory
*
* @param StreamFactoryInterface $streamFactory
* @return self
*/
public function withStreamFactory(
StreamFactoryInterface $streamFactory
): self {
return $this->with('streamFactory', $streamFactory);
}
/**
* Set the cache
*
* @param CacheInterface|null $cache
* @return self
*/
public function withCache(?CacheInterface $cache): self
{
if (is_null($cache)) {
$this->with('cache', null);
}
return $this->with(
'cache',
new Cache($cache, $this->cachePrefix, $this->timeToLive)
);
}
/**
* Check if Cache is set
*
* @return boolean
*/
public function hasCache(): bool
{
return !is_null($this->cache);
}
/**
* Get the Cache Wrapper
*
* @return Cache|null
*/
public function getCache(): ?Cache
{
return $this->cache;
}
/**
* Set Cache Time To Live
*
* @param integer|null $timeToLive
* @return self
*/
public function withTimeToLive(?int $timeToLive = null): self
{
return $this->with('timeToLive', $timeToLive);
}
/**
* Set the value of cachePrefix
*
* @param string $cachePrefix
*
* @return self
*/
public function withCachePrefix(string $cachePrefix): self
{
return $this->with('cachePrefix', $cachePrefix);
}
/**
* Should the cache be skipped (but still updated)
*
* @return bool
*/
public function skipCache(): bool
{
return $this->skipCache;
}
/**
* Whether to Skip Cache (but still update it)
*
* @param bool $skipCache
*
* @return self
*/
public function withSkipCache(bool $skipCache): self
{
return $this->with('skipCache', $skipCache);
}
/**
* Whether to use the Cache as a failover for server errors
*
* @param bool $useCacheAsFailover
*
* @return self
*/
public function withUseCacheAsFailover(bool $useCacheAsFailover): self
{
return $this->with('useCacheAsFailover', $useCacheAsFailover);
}
/**
* Get the environment model.
* @return EnvironmentModel|null
*/
public function getEnvironment(): ?EnvironmentModel
{
return $this->environment;
}
/**
* Get all the default for flags for the current environment.
* @return Flags
*
* @throws FlagsmithThrowable
*/
public function getEnvironmentFlags(): Flags
{
if ($this->environment) {
return $this->getEnvironmentFlagsFromDocument();
}
return $this->getEnvironmentFlagsFromApi();
}
/**
* Get all the flags for the current environment for a given identity. Will also
* upsert all traits to the Flagsmith API for future evaluations. Providing a
* trait with a value of None will remove the trait from the identity if it exists.
* @param string $identifier
* @param object|null $traits
* @return Flags
*
* @throws FlagsmithThrowable
*/
public function getIdentityFlags(string $identifier, ?object $traits = null): Flags
{
$traits = $traits ?? (object) [];
if ($this->environment) {
return $this->getIdentityFlagsFromDocument($identifier, $traits);
}
return $this->getIdentityFlagsFromApi($identifier, $traits);
}
/**
* Get a list of segments that the given identity is in.
* @param string $identifier a unique identifier for the identity in the current
* environment , e.g. email address, username, uuid
* @param object|null $traits a dictionary of traits to add / update on the identity in
* Flagsmith, e.g. {"num_orders": 10}
* @return array
*
* @throws FlagsmithThrowable
*/
public function getIdentitySegments(string $identifier, ?object $traits = null): array
{
if (empty($this->environment)) {
throw new FlagsmithClientError('Local evaluation required to obtain identity segments.');
}
$traits = $traits ?? (object)[];
$identityModel = $this->getIdentityModel($identifier, $traits);
$segmentModels = SegmentEvaluator::getIdentitySegments($this->environment, $identityModel);
return array_map(fn ($segment) => (new Segment())
->withId($segment->getId())
->withName($segment->getName()), $segmentModels);
}
/**
* Externalised method to update the environement cache.
* @return void
*
* @throws FlagsmithThrowable
*/
public function updateEnvironment()
{
if (is_int($this->environmentTtl)) {
$this->environment = $this->getEnvironmentFromApi();
}
}
/**
* Get the environment API.
* @return EnvironmentModel
*
* @throws FlagsmithAPIError
*/
protected function getEnvironmentFromApi(): EnvironmentModel
{
$environmentDict = $this->cachedCall('Environment', 'GET', $this->environment_url, [], false, $this->environmentTtl);
return EnvironmentModel::build($environmentDict);
}
/**
* Get the environment flags from document.
* @return Flags
*/
protected function getEnvironmentFlagsFromDocument(): Flags
{
return Flags::fromFeatureStateModels(
new FeatureStateModelList(Engine::getEnvironmentFeatureStates($this->environment)),
$this->analyticsProcessor,
$this->defaultFlagHandler
);
}
/**
* Get identiity flags from document
* @param string $identifier
* @param object $traits
* @return Flags
*
* @throws FlagsmithClientError
*/
protected function getIdentityFlagsFromDocument(string $identifier, object $traits): Flags
{
$identityModel = $this->getIdentityModel($identifier, $traits);
$featureStates = Engine::getIdentityFeatureStates($this->environment, $identityModel);
return Flags::fromFeatureStateModels(
new FeatureStateModelList($featureStates),
$this->analyticsProcessor,
$this->defaultFlagHandler,
$identityModel->compositeKey(),
);
}
/**
* Get environment flags from API.
* @return Flags
*
* @throws FlagsmithAPIError
*/
protected function getEnvironmentFlagsFromApi(): Flags
{
try {
$apiFlags = $this->cachedCall('Global', 'GET', $this->environment_flags_url);
return Flags::fromApiFlags(
(object) $apiFlags,
$this->analyticsProcessor,
$this->defaultFlagHandler,
);
} catch (FlagsmithAPIError $e) {
if (isset($this->defaultFlagHandler)) {
return (new Flags())
->withDefaultFlagHandler($this->defaultFlagHandler);
}
throw $e;
}
}
/**
* Get the identity flags from API.
*
* @return Flags
*
* @throws FlagsmithAPIError
*/
protected function getIdentityFlagsFromApi(string $identifier, ?object $traits): Flags
{
try {
$data = IdentitiesGenerator::generateIdentitiesData($identifier, $traits);
$cacheKey = IdentitiesGenerator::generateIdentitiesCacheKey($identifier, $traits);
$apiFlags = $this->cachedCall(
$cacheKey,
'POST',
$this->identities_url,
$data
);
return Flags::fromApiFlags(
(object) $apiFlags->flags,
$this->analyticsProcessor,
$this->defaultFlagHandler,
);
} catch (FlagsmithAPIError $e) {
if (isset($this->defaultFlagHandler)) {
return (new Flags())
->withDefaultFlagHandler($this->defaultFlagHandler);
}
throw $e;
}
}
/**
* Buid with identity model.
* @param string $identifier
* @param array|null $traits
* @return IdentityModel
*
* @throws FlagsmithClientError
*/
private function getIdentityModel(string $identifier, ?object $traits): IdentityModel
{
if (empty($this->environment)) {
throw new FlagsmithClientError('Unable to build identity model when no local environment present.');
}
$traitModels = [];
foreach ($traits as $key => $value) {
$traitModels[] = (new TraitModel())
->withTraitKey($key)
->withTraitValue($value);
}
$identityModel = isset($this->environment->identity_overrides) ? $this->environment->identity_overrides[$identifier] ?? null : null;
if (is_null($identityModel)) {
return (new IdentityModel())
->withIdentifier($identifier)
->withEnvironmentApiKey($this->apiKey)
->withIdentityTraits(new IdentityTraitList($traitModels));
}
return $identityModel->withIdentityTraits(new IdentityTraitList($traitModels));
}
/**
* Call the API and cache the response (If Caching is Enabled)
*
* @param string $cacheKey
* @param string $method
* @param string $uri
* @param array $body
* @param boolean $skipCache
* @return object|array
*
* @throws FlagsmithAPIError
*/
private function cachedCall(
string $cacheKey,
string $method,
string $uri,
array $body = [],
bool $skipCache = false,
?int $ttl = null
) {
if (!$this->hasCache()) {
return $this->call($method, $uri, $body);
}
if (!$skipCache && !$this->skipCache()) {
$cachedCall = $this->cache->get($cacheKey);
if (\is_array($cachedCall) || \is_object($cachedCall)) {
return $cachedCall;
}
}
try {
$response = $this->call($method, $uri, $body);
$this->cache->set($cacheKey, $response, $ttl);
return $response;
} catch (FlagsmithAPIError $e) {
if ($this->useCacheAsFailover) {
$cachedCall = $this->cache->get($cacheKey);
if (\is_array($cachedCall) || \is_object($cachedCall)) {
return $cachedCall;
}
}
throw $e;
}
}
/**
* Call Request
*
* This sets up a FIG PSR-7 request and returns the response through a PSR-18 call
*
* Note: We use Guzzle's Request here to construct a PSR-7 RequestInterface
*
* @param string $method
* @param string $uri
* @param array $body
* @return object|array
*
* @throws FlagsmithAPIError
*/
private function call(string $method, string $uri, array $body = [])
{
$stream = $this->streamFactory->createStream(json_encode($body));
$request = $this->requestFactory
->createRequest($method, rtrim($this->host, '/') . '/' . $uri)
->withHeader('Accept', 'application/json')
->withHeader('Content-Type', 'application/json')
->withHeader('X-Environment-Key', $this->apiKey);
if (!empty($this->customHeaders)) {
foreach ($this->customHeaders as $name => $value) {
$request = $request->withHeader($name, $value);
}
}
if ($method !== 'GET') {
$request = $request->withBody($stream);
}
$response = null;
$retry = clone ($this->retries);
$statusCode = null;
do {
$retry->waitWithBackoff();
// sets to true on last try
$throwException = !$retry->hasRetriesRemaining();
try {
$response = $this->client->sendRequest($request);
} catch (\Exception $e) {
if ($throwException) {
throw new FlagsmithAPIError($e->getMessage(), $e->getCode(), $e);
}
}
if ($response) {
$statusCode = $response->getStatusCode();
if ($statusCode === 200) {
// request was successful.
break;
} elseif ($throwException && $statusCode !== 200) {
$message = $response->getBody()->getContents();
try {
$error = json_decode($message, true, 512, JSON_THROW_ON_ERROR);
if (!empty($error['detail'])) {
$message = $error['detail'];
}
} catch (JsonException $e) {
}
throw new FlagsmithAPIError($message);
}
}
$retry->retryAttempted();
} while ($retry->isRetry($statusCode));
if ($response) {
//Return as array, easier to work with in PHP
return json_decode(
$response->getBody()->getContents(),
false,
512,
JSON_THROW_ON_ERROR
);
}
throw new FlagsmithAPIError('No response received!');
}
}