1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gbowo\Traits; |
4
|
|
|
|
5
|
|
|
use LogicException; |
6
|
|
|
use Gbowo\Contract\Plugin\PluginInterface; |
7
|
|
|
use Gbowo\Contract\Adapter\AdapterInterface; |
8
|
|
|
use Gbowo\Exception\PluginNotFoundException; |
9
|
|
|
|
10
|
|
|
trait Pluggable |
11
|
|
|
{ |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var PluginInterface[] |
15
|
|
|
*/ |
16
|
|
|
protected $plugins = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Add a plugin |
20
|
|
|
* @param \Gbowo\Contract\Plugin\PluginInterface $plugin |
21
|
|
|
* @return $this |
22
|
|
|
*/ |
23
|
43 |
|
public function addPlugin(PluginInterface $plugin) |
24
|
|
|
{ |
25
|
43 |
|
$this->plugins[$plugin->getPluginAccessor()] = $plugin; |
26
|
|
|
|
27
|
43 |
|
return $this; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Magic method to allow for a plugin call |
32
|
|
|
* @param string $pluginAccessor |
33
|
|
|
* @param array $argument |
34
|
|
|
* @return mixed |
35
|
|
|
*/ |
36
|
31 |
|
public function __call( |
37
|
|
|
string $pluginAccessor, |
38
|
|
|
array $argument |
39
|
|
|
) { |
40
|
31 |
|
return $this->callPlugin($pluginAccessor, $argument, $this); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $accessor The plugin accessor |
45
|
|
|
* @param array $argument Args to pass to the plugin's `handle` method |
46
|
|
|
* @param \Gbowo\Contract\Adapter\AdapterInterface $adapter The adapter in use. |
47
|
|
|
* @throws \LogicException if the plugin does not have an handle method |
48
|
|
|
* @return mixed |
49
|
|
|
*/ |
50
|
31 |
|
public function callPlugin( |
51
|
|
|
string $accessor, |
52
|
|
|
array $argument, |
53
|
|
|
AdapterInterface $adapter |
54
|
|
|
) { |
55
|
31 |
|
$plugin = $this->getPlugin($accessor); |
56
|
31 |
|
$plugin->setAdapter($adapter); |
57
|
|
|
|
58
|
31 |
|
if (method_exists($plugin, "handle")) { |
59
|
31 |
|
return $plugin->handle(...$argument); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
throw new LogicException( |
63
|
|
|
"A Plugin MUST have an handle method" |
64
|
|
|
); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param string $accessor |
69
|
|
|
* @return \Gbowo\Contract\Plugin\PluginInterface |
70
|
|
|
* @throws \Gbowo\Exception\PluginNotFoundException If the plugin cannot be found |
71
|
|
|
*/ |
72
|
31 |
|
public function getPlugin(string $accessor) |
73
|
|
|
{ |
74
|
31 |
|
if (!isset($this->plugins[$accessor])) { |
75
|
|
|
throw new PluginNotFoundException( |
76
|
|
|
"Plugin with accessor, {$accessor} not found" |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
|
80
|
31 |
|
return $this->plugins[$accessor]; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|