|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Acclimate\Container; |
|
4
|
|
|
|
|
5
|
|
|
use Acclimate\Container\Exception\InvalidAdapterException; |
|
6
|
|
|
use Interop\Container\ContainerInterface; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* This class is used to "acclimate", or adapt, a container object (e.g., DIC, SL) to a common ContainerInterface. In |
|
10
|
|
|
* terms of design patterns, it's essentially a `factory` for `adapter`s |
|
11
|
|
|
*/ |
|
12
|
|
|
class ContainerAcclimator |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var array Map of container classes to container adapter classes |
|
16
|
|
|
*/ |
|
17
|
|
|
private $adapterMap; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param array $customAdapterMap Overwrite the predefined adapter map |
|
21
|
|
|
*/ |
|
22
|
5 |
|
public function __construct(array $customAdapterMap = null) |
|
23
|
|
|
{ |
|
24
|
5 |
|
$this->adapterMap = is_array($customAdapterMap) ? $customAdapterMap : include 'Adapter/map.php'; |
|
25
|
5 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Registers a custom adapter for a class by mapping the fully qualified class name (FQCN) of one to the other |
|
29
|
|
|
* |
|
30
|
|
|
* @param string $adapterFqcn The FQCN of the adapter class |
|
31
|
|
|
* @param string $adapteeFqcn The FQCN of the class being adapted |
|
32
|
|
|
* |
|
33
|
|
|
* @return ContainerAcclimator |
|
34
|
|
|
*/ |
|
35
|
1 |
|
public function registerAdapter($adapterFqcn, $adapteeFqcn) |
|
36
|
|
|
{ |
|
37
|
1 |
|
$this->adapterMap[$adapteeFqcn] = $adapterFqcn; |
|
38
|
|
|
|
|
39
|
1 |
|
return $this; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Adapts an object by wrapping it with a registered adapter class that implements an Acclimate interface |
|
44
|
|
|
* |
|
45
|
|
|
* @param mixed $adaptee A third-party object to be acclimated |
|
46
|
|
|
* |
|
47
|
|
|
* @return ContainerInterface |
|
48
|
|
|
* @throws InvalidAdapterException if there is no adapter found for the provided object |
|
49
|
|
|
*/ |
|
50
|
4 |
|
public function acclimate($adaptee) |
|
51
|
|
|
{ |
|
52
|
4 |
|
if ($adaptee instanceof ContainerInterface) { |
|
53
|
|
|
// If the adaptee already implements the ContainerInterface, just return it |
|
54
|
1 |
|
return $adaptee; |
|
55
|
|
|
} else { |
|
56
|
|
|
// Otherwise, check the adapter map to see if there is an appropriate adapter registered |
|
57
|
3 |
|
foreach ($this->adapterMap as $adapteeFqcn => $adapterFqcn) { |
|
58
|
3 |
|
if ($adaptee instanceof $adapteeFqcn) { |
|
59
|
2 |
|
return new $adapterFqcn($adaptee); |
|
60
|
|
|
} |
|
61
|
3 |
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
// If no adapter matches the provided container object, throw an exception |
|
65
|
1 |
|
throw InvalidAdapterException::fromAdaptee($adaptee); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|