1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Stratadox\Proxy; |
4
|
|
|
|
5
|
|
|
use Stratadox\Proxy\When\KeyMatches; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* CompositeProxyFactory. Creates a proxy, choosing its concrete implementation |
9
|
|
|
* based on the known data for the proxied entity. |
10
|
|
|
* |
11
|
|
|
* @author Stratadox |
12
|
|
|
*/ |
13
|
|
|
final class CompositeProxyFactory implements ProxyFactory |
14
|
|
|
{ |
15
|
|
|
private $choices; |
16
|
|
|
|
17
|
|
|
private function __construct(Choice ...$choices) |
18
|
|
|
{ |
19
|
|
|
$this->choices = $choices; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Makes a new composite factory that decides on a proxy implementation |
24
|
|
|
* based on a key. |
25
|
|
|
* |
26
|
|
|
* @param string $key The key to check for. |
27
|
|
|
* @param array $factories A set of expected values with associated factory. |
28
|
|
|
* @return ProxyFactory The composite factory that decides based on a key. |
29
|
|
|
*/ |
30
|
|
|
public static function decidingBy(string $key, array $factories): ProxyFactory |
31
|
|
|
{ |
32
|
|
|
$choices = []; |
33
|
|
|
foreach ($factories as $value => $factory) { |
34
|
|
|
$choices[] = Maybe::the($factory, KeyMatches::with($key, $value)); |
35
|
|
|
} |
36
|
|
|
return new self(...$choices); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Makes a new composite factory that decides on a proxy implementation |
41
|
|
|
* based on a set of choices. |
42
|
|
|
* |
43
|
|
|
* @param Choice ...$choices The choices to involve. |
44
|
|
|
* @return ProxyFactory The composite factory. |
45
|
|
|
*/ |
46
|
|
|
public static function using(Choice ...$choices): ProxyFactory |
47
|
|
|
{ |
48
|
|
|
return new self(...$choices); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** @inheritdoc */ |
52
|
|
|
public function create(array $knownData = []): Proxy |
53
|
|
|
{ |
54
|
|
|
foreach ($this->choices as $choice) { |
55
|
|
|
if ($choice->shouldUseFor($knownData)) { |
56
|
|
|
return $choice->create($knownData); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
throw NoFactoryFound::forData($knownData); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|