forked from laravel/pennant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecorator.php
More file actions
862 lines (735 loc) · 23.5 KB
/
Decorator.php
File metadata and controls
862 lines (735 loc) · 23.5 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
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
<?php
namespace Laravel\Pennant\Drivers;
use Closure;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Lottery;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Laravel\Pennant\Contracts\CanListStoredFeatures;
use Laravel\Pennant\Contracts\DefinesFeaturesExternally;
use Laravel\Pennant\Contracts\Driver;
use Laravel\Pennant\Contracts\FeatureScopeable;
use Laravel\Pennant\Contracts\HasFlushableCache;
use Laravel\Pennant\Events\AllFeaturesPurged;
use Laravel\Pennant\Events\DynamicallyRegisteringFeatureClass;
use Laravel\Pennant\Events\FeatureDeleted;
use Laravel\Pennant\Events\FeatureResolved;
use Laravel\Pennant\Events\FeatureRetrieved;
use Laravel\Pennant\Events\FeaturesPurged;
use Laravel\Pennant\Events\FeatureUpdated;
use Laravel\Pennant\Events\FeatureUpdatedForAllScopes;
use Laravel\Pennant\Events\UnexpectedNullScopeEncountered;
use Laravel\Pennant\Feature;
use Laravel\Pennant\LazilyResolvedFeature;
use Laravel\Pennant\PendingScopedFeatureInteraction;
use ReflectionClass;
use ReflectionFunction;
use ReflectionIntersectionType;
use ReflectionNamedType;
use ReflectionUnionType;
use RuntimeException;
use Symfony\Component\Finder\Finder;
/**
* @mixin \Laravel\Pennant\PendingScopedFeatureInteraction
*/
class Decorator implements CanListStoredFeatures, Driver, HasFlushableCache
{
use Macroable {
__call as macroCall;
}
/**
* The driver name.
*
* @var string
*/
protected $name;
/**
* The driver being decorated.
*
* @var \Laravel\Pennant\Contracts\Driver
*/
protected $driver;
/**
* The default scope resolver.
*
* @var callable(): mixed
*/
protected $defaultScopeResolver;
/**
* The container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* The in-memory feature state cache.
*
* @var \Illuminate\Support\Collection<int, array{ feature: string, scope: mixed, value: mixed }>
*/
protected $cache;
/**
* Map of feature names to their implementations.
*
* @var array<string, mixed>
*/
protected $nameMap = [];
/**
* Create a new driver decorator instance.
*
* @param string $name
* @param \Laravel\Pennant\Contracts\Driver $driver
* @param (callable(): mixed) $defaultScopeResolver
* @param \Illuminate\Contracts\Container\Container $container
* @param \Illuminate\Support\Collection<int, array{ feature: string, scope: mixed, value: mixed }> $cache
*/
public function __construct($name, $driver, $defaultScopeResolver, $container, $cache)
{
$this->name = $name;
$this->driver = $driver;
$this->defaultScopeResolver = $defaultScopeResolver;
$this->container = $container;
$this->cache = $cache;
}
/**
* Discover and register the application's feature classes.
*
* @param string $namespace
* @param string|null $path
* @return void
*/
public function discover($namespace = 'App\\Features', $path = null)
{
$namespace = Str::finish($namespace, '\\');
Collection::make((new Finder)
->files()
->name('*.php')
->depth(0)
->in($path ?? base_path('app/Features')))
->each(fn ($file) => $this->define("{$namespace}{$file->getBasename('.php')}"));
}
/**
* Define an initial feature flag state resolver.
*
* @param string|class-string $feature
* @param mixed $resolver
*/
public function define($feature, $resolver = null): void
{
if (func_num_args() === 1) {
[$feature, $resolver] = [
$this->container->make($feature)->name ?? $feature,
new LazilyResolvedFeature($feature),
];
$this->nameMap[$feature] = $resolver->feature;
} else {
$this->nameMap[$feature] = $resolver;
}
$this->driver->define($feature, function ($scope) use ($feature, $resolver) {
if ($resolver instanceof LazilyResolvedFeature) {
$resolver = with($this->container[$resolver->feature], fn ($instance) => method_exists($instance, 'resolve')
? $instance->resolve(...) // @phpstan-ignore callable.nonNativeMethod
: $instance(...));
}
if (! $resolver instanceof Closure) {
return $this->resolve($feature, fn () => $resolver, $scope);
}
if ($scope !== null) {
return $this->resolve($feature, $resolver, $scope);
}
if ($this->canHandleNullScope($resolver)) {
return $this->resolve($feature, $resolver, $scope);
}
Event::dispatch(new UnexpectedNullScopeEncountered($feature));
return $this->resolve($feature, fn () => false, $scope);
});
}
/**
* Resolve the feature value.
*
* @param string $feature
* @param callable $resolver
* @param mixed $scope
* @return mixed
*/
protected function resolve($feature, $resolver, $scope)
{
$value = $resolver($scope);
$value = $value instanceof Lottery ? $value() : $value;
Event::dispatch(new FeatureResolved($feature, $scope, $value));
return $value;
}
/**
* Determine if the resolver can handle the scope.
*
* @param callable|class-string $resolver
* @param mixed $scope
* @return bool
*/
public function isResolverValidForScope($resolver, $scope)
{
if (is_string($resolver) && class_exists($resolver)) {
$class = new ReflectionClass($resolver);
$function = $class->hasMethod('resolve')
? $class->getMethod('resolve')
: $class->getMethod('__invoke');
} else {
$function = new ReflectionFunction(Closure::fromCallable($resolver));
}
if ($function->getNumberOfParameters() === 0) {
return true;
}
$type = $function->getParameters()[0]->getType();
if ($type === null) {
return true;
}
return $this->typeAllowsScope($type, $scope, $function);
}
/**
* Determine if the type can handle the scope.
*
* @param \ReflectionType $type
* @param mixed $scope
* @param \ReflectionMethod|\ReflectionFunction $function
* @return bool
*/
protected function typeAllowsScope($type, $scope, $function)
{
if ($type instanceof ReflectionUnionType) {
foreach ($type->getTypes() as $type) {
if ($this->typeAllowsScope($type, $scope, $function)) {
return true;
}
}
return false;
}
if ($type instanceof ReflectionIntersectionType) {
foreach ($type->getTypes() as $type) {
if (! $this->typeAllowsScope($type, $scope, $function)) {
return false;
}
}
return true;
}
if ($type instanceof ReflectionNamedType) {
if ($type->getName() === 'mixed') {
return true;
}
return match (gettype($scope)) {
'boolean',
'integer',
'double',
'string',
'array',
'resource',
'resource (closed)' => gettype($scope) === $type->getName(),
'NULL' => $this->canHandleNullScope($function),
'object' => $scope instanceof ($type->getName()),
'unknown type' => false,
};
}
throw new RuntimeException('Unknown reflection type encoutered.');
}
/**
* Determine if the resolver accepts null scope.
*
* @param callable|\ReflectionFunction|\ReflectionMethod $resolver
* @return bool
*/
protected function canHandleNullScope($resolver)
{
$function = is_callable($resolver)
? new ReflectionFunction(Closure::fromCallable($resolver))
: $resolver;
return $function->getNumberOfParameters() === 0 ||
! $function->getParameters()[0]->hasType() ||
$function->getParameters()[0]->getType()->allowsNull();
}
/**
* Retrieve the names of all defined features.
*
* @return array<string>
*/
public function defined(): array
{
return $this->driver->defined();
}
/**
* Retrieve the names of all stored features.
*
* @return array<string>
*/
public function stored(): array
{
if (! $this->driver instanceof CanListStoredFeatures) {
throw new RuntimeException("The [{$this->name}] driver does not support listing stored features.");
}
return $this->driver->stored();
}
/**
* Get multiple feature flag values.
*
* @internal
*
* @param string|array<int|string, mixed> $features
* @return array<string, array<int, mixed>>
*/
public function getAll($features): array
{
$features = $this->normalizeFeaturesToLoad($features);
if ($features->isEmpty()) {
return [];
}
$hasUnresolvedFeatures = false;
$resolvedBefore = $features->reduce(function ($resolved, $scopes, $feature) use (&$hasUnresolvedFeatures) {
$resolved[$feature] = [];
if (! $this->hasBeforeHook($feature)) {
$hasUnresolvedFeatures = true;
return $resolved;
}
$before = $this->container->make($this->implementationClass($feature))->before(...);
foreach ($scopes as $index => $scope) {
$value = $this->resolveBeforeHook($feature, $scope, $before);
if ($value !== null) {
$resolved[$feature][$index] = $value;
} else {
$hasUnresolvedFeatures = true;
}
}
return $resolved;
}, []);
$results = array_replace_recursive(
$features->all(),
$resolvedBefore,
$hasUnresolvedFeatures ? $this->driver->getAll($features->map(function ($scopes, $feature) use ($resolvedBefore) {
return array_diff_key($scopes, $resolvedBefore[$feature]);
})->all()) : [],
);
$features->flatMap(fn ($scopes, $key) => Collection::make($scopes)
->zip($results[$key])
->map(fn ($scopes) => $scopes->push($key)))
->each(fn ($value) => $this->putInCache($value[2], $value[0], $value[1]));
return $results;
}
/**
* Get multiple feature flag values that are missing.
*
* @internal
*
* @param string|array<int|string, mixed> $features
* @return array<string, array<int, mixed>>
*/
public function getAllMissing($features)
{
return $this->normalizeFeaturesToLoad($features)
->map(fn ($scopes, $feature) => Collection::make($scopes)
->reject(fn ($scope) => $this->isCached($feature, $scope))
->all())
->reject(fn ($scopes) => $scopes === [])
->pipe(fn ($features) => $this->getAll($features->all()));
}
/**
* Normalize the features to load.
*
* @param string|array<int|string, mixed> $features
* @return \Illuminate\Support\Collection<string, array<int, mixed>>
*/
protected function normalizeFeaturesToLoad($features)
{
return Collection::wrap($features)
->mapWithKeys(fn ($value, $key) => is_int($key)
? [$value => Collection::make([$this->defaultScope()])]
: [$key => Collection::wrap($value)])
->mapWithKeys(fn ($scopes, $feature) => [
$this->resolveFeature($feature) => $scopes,
])
->map(
fn ($scopes) => $scopes->map(fn ($scope) => $this->resolveScope($scope))->all()
);
}
/**
* Retrieve a feature flag's value.
*
* @internal
*
* @param string $feature
* @param mixed $scope
*/
public function get($feature, $scope): mixed
{
$feature = $this->resolveFeature($feature);
$scope = $this->resolveScope($scope);
$item = $this->cache
->whereStrict('scope', Feature::serializeScope($scope))
->whereStrict('feature', $feature)
->first();
if ($item !== null) {
Event::dispatch(new FeatureRetrieved($feature, $scope, $item['value']));
return $item['value'];
}
$before = $this->hasBeforeHook($feature)
? $this->container->make($this->implementationClass($feature))->before(...)
: fn () => null;
$value = $this->resolveBeforeHook($feature, $scope, $before) ?? $this->driver->get($feature, $scope);
$this->putInCache($feature, $scope, $value);
Event::dispatch(new FeatureRetrieved($feature, $scope, $value));
return $value;
}
/**
* Resolve the before hook value.
*
* @param string $feature
* @param mixed $scope
* @param callable $hook
* @return mixed
*/
protected function resolveBeforeHook($feature, $scope, $hook)
{
if ($scope === null && ! $this->canHandleNullScope($hook)) {
Event::dispatch(new UnexpectedNullScopeEncountered($feature));
return null;
}
return $hook($scope);
}
/**
* Set a feature flag's value.
*
* @internal
*
* @param string $feature
* @param mixed $scope
* @param mixed $value
*/
public function set($feature, $scope, $value): void
{
$feature = $this->resolveFeature($feature);
$scope = $this->resolveScope($scope);
$this->driver->set($feature, $scope, $value);
$this->putInCache($feature, $scope, $value);
Event::dispatch(new FeatureUpdated($feature, $scope, $value));
}
/**
* Activate the feature for everyone.
*
* @param string|array<string> $feature
* @param mixed $value
* @return void
*/
public function activateForEveryone($feature, $value = true)
{
Collection::wrap($feature)
->each(fn ($name) => $this->setForAllScopes($name, $value));
}
/**
* Deactivate the feature for everyone.
*
* @param string|array<string> $feature
* @return void
*/
public function deactivateForEveryone($feature)
{
Collection::wrap($feature)
->each(fn ($name) => $this->setForAllScopes($name, false));
}
/**
* Set a feature flag's value for all scopes.
*
* @internal
*
* @param string $feature
* @param mixed $value
*/
public function setForAllScopes($feature, $value): void
{
$feature = $this->resolveFeature($feature);
$this->driver->setForAllScopes($feature, $value);
$this->cache = $this->cache->reject(
fn ($item) => $item['feature'] === $feature
);
Event::dispatch(new FeatureUpdatedForAllScopes($feature, $value));
}
/**
* Delete a feature flag's value.
*
* @internal
*
* @param string $feature
* @param mixed $scope
*/
public function delete($feature, $scope): void
{
$feature = $this->resolveFeature($feature);
$scope = $this->resolveScope($scope);
$this->driver->delete($feature, $scope);
$this->removeFromCache($feature, $scope);
Event::dispatch(new FeatureDeleted($feature, $scope));
}
/**
* Purge the given feature from storage.
*
* @param string|array|null $features
*/
public function purge($features = null): void
{
if ($features === null) {
$this->driver->purge(null);
$this->cache = new Collection;
Event::dispatch(new AllFeaturesPurged);
} else {
Collection::wrap($features)
->map($this->resolveFeature(...))
->pipe(function ($features) {
$this->driver->purge($features->all());
$this->cache->forget(
$this->cache->whereInStrict('feature', $features)->keys()->all()
);
Event::dispatch(new FeaturesPurged($features->all()));
});
}
}
/**
* Retrieve the feature's name.
*
* @param string $feature
* @return string
*/
public function name($feature)
{
return $this->resolveFeature($feature);
}
/**
* Retrieve the map of feature names to their implementations.
*/
public function nameMap(): array
{
return $this->nameMap;
}
/**
* Retrieve the feature's class.
*
* @template TFlag
*
* @param TFlag|string $name
* @return (TFlag is class-string<TFlag> ? TFlag : mixed)
*/
public function instance($name)
{
$feature = $this->nameMap[$name] ?? $name;
if (is_string($feature) && class_exists($feature)) {
return $this->container->make($feature);
}
if ($feature instanceof Closure || $feature instanceof Lottery) {
return $feature;
}
return fn () => $feature;
}
/**
* Retrieve the defined features for the given scope.
*
* @internal
*
* @param mixed $scope
* @return \Illuminate\Support\Collection<int, string>
*/
public function definedFeaturesForScope($scope)
{
$scope = $this->resolveScope($scope);
if ($this->driver instanceof DefinesFeaturesExternally) {
return collect($this->driver->definedFeaturesForScope($scope));
}
return collect($this->nameMap)
->only($this->defined())
->filter(function ($resolver) use ($scope) {
if (is_callable($resolver) || (is_string($resolver) && class_exists($resolver))) {
return $this->isResolverValidForScope($resolver, $scope);
}
return true;
})
->keys();
}
/**
* Resolve the feature name and ensure it is defined.
*
* @param string $feature
* @return string
*/
protected function resolveFeature($feature)
{
return $this->shouldDynamicallyDefine($feature)
? $this->ensureDynamicFeatureIsDefined($feature)
: $feature;
}
/**
* Determine if the feature should be dynamically defined.
*
* @param string $feature
* @return bool
*/
protected function shouldDynamicallyDefine($feature)
{
return ! in_array($feature, $this->defined())
&& class_exists($feature)
&& (method_exists($feature, 'resolve') || method_exists($feature, '__invoke'));
}
/**
* Dynamically define the feature.
*
* @param string $feature
* @return string
*/
protected function ensureDynamicFeatureIsDefined($feature)
{
return tap($this->container->make($feature)->name ?? $feature, function ($name) use ($feature) {
if (! in_array($name, $this->defined())) {
Event::dispatch(new DynamicallyRegisteringFeatureClass($feature));
$this->define($feature);
}
});
}
/**
* Determine if the given feature has a before hook.
*
* @param string $feature
* @return bool
*/
protected function hasBeforeHook($feature)
{
$implementation = $this->implementationClass($feature);
return is_string($implementation) && class_exists($implementation) && method_exists($implementation, 'before');
}
/**
* Retrieve the implementation feature class for the given feature name.
*
* @return ?string
*/
protected function implementationClass($feature)
{
$class = $this->nameMap[$feature] ?? $feature;
if (is_string($class) && class_exists($class)) {
return $class;
}
return null;
}
/**
* Resolve the scope.
*
* @param mixed $scope
* @return mixed
*/
protected function resolveScope($scope)
{
return $scope instanceof FeatureScopeable
? $scope->toFeatureIdentifier($this->name)
: $scope;
}
/**
* Determine if a feature's value is in the cache for the given scope.
*
* @param string $feature
* @param mixed $scope
* @return bool
*/
protected function isCached($feature, $scope)
{
$scope = Feature::serializeScope($scope);
return $this->cache->search(
fn ($item) => $item['feature'] === $feature && $item['scope'] === $scope
) !== false;
}
/**
* Put the given feature's value into the cache.
*
* @param string $feature
* @param mixed $scope
* @param mixed $value
* @return void
*/
protected function putInCache($feature, $scope, $value)
{
$scope = Feature::serializeScope($scope);
$position = $this->cache->search(
fn ($item) => $item['feature'] === $feature && $item['scope'] === $scope
);
if ($position === false) {
$this->cache[] = ['feature' => $feature, 'scope' => $scope, 'value' => $value];
} else {
$this->cache[$position] = ['feature' => $feature, 'scope' => $scope, 'value' => $value];
}
}
/**
* Remove the given feature's value from the cache.
*
* @param string $feature
* @param mixed $scope
* @return void
*/
protected function removeFromCache($feature, $scope)
{
$scope = Feature::serializeScope($scope);
$position = $this->cache->search(
fn ($item) => $item['feature'] === $feature && $item['scope'] === $scope
);
if ($position !== false) {
unset($this->cache[$position]);
}
}
/**
* Retrieve the default scope.
*
* @return mixed
*/
protected function defaultScope()
{
return ($this->defaultScopeResolver)();
}
/**
* Flush the in-memory cache of feature values.
*
* @return void
*/
public function flushCache()
{
$this->cache = new Collection;
if ($this->driver instanceof HasFlushableCache) {
$this->driver->flushCache();
}
}
/**
* Get the underlying feature driver.
*
* @return \Laravel\Pennant\Contracts\Driver
*/
public function getDriver()
{
return $this->driver;
}
/**
* Set the container instance used by the decorator.
*
* @return $this
*/
public function setContainer(Container $container)
{
$this->container = $container;
return $this;
}
/**
* Dynamically create a pending feature interaction.
*
* @param string $name
* @param array<mixed> $parameters
* @return mixed
*/
public function __call($name, $parameters)
{
if (static::hasMacro($name)) {
return $this->macroCall($name, $parameters);
}
return tap(new PendingScopedFeatureInteraction($this), function ($interaction) use ($name) {
if ($name !== 'for' && ($this->defaultScopeResolver)() !== null) {
$interaction->for(($this->defaultScopeResolver)());
}
})->{$name}(...$parameters);
}
}