-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPluggable.php
82 lines (70 loc) · 2.11 KB
/
Pluggable.php
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
<?php
namespace Gbowo\Traits;
use LogicException;
use Gbowo\Contract\Plugin\PluginInterface;
use Gbowo\Contract\Adapter\AdapterInterface;
use Gbowo\Exception\PluginNotFoundException;
trait Pluggable
{
/**
* @var PluginInterface[]
*/
protected $plugins = [];
/**
* Add a plugin
* @param \Gbowo\Contract\Plugin\PluginInterface $plugin
* @return $this
*/
public function addPlugin(PluginInterface $plugin)
{
$this->plugins[$plugin->getPluginAccessor()] = $plugin;
return $this;
}
/**
* Magic method to allow for a plugin call
* @param string $pluginAccessor
* @param array $argument
* @return mixed
*/
public function __call(
string $pluginAccessor,
array $argument
) {
return $this->callPlugin($pluginAccessor, $argument, $this);
}
/**
* @param string $accessor The plugin accessor
* @param array $argument Args to pass to the plugin's `handle` method
* @param \Gbowo\Contract\Adapter\AdapterInterface $adapter The adapter in use.
* @throws \LogicException if the plugin does not have an handle method
* @return mixed
*/
public function callPlugin(
string $accessor,
array $argument,
AdapterInterface $adapter
) {
$plugin = $this->getPlugin($accessor);
$plugin->setAdapter($adapter);
if (method_exists($plugin, "handle")) {
return $plugin->handle(...$argument);
}
throw new LogicException(
"A Plugin MUST have an handle method"
);
}
/**
* @param string $accessor
* @return \Gbowo\Contract\Plugin\PluginInterface
* @throws \Gbowo\Exception\PluginNotFoundException If the plugin cannot be found
*/
public function getPlugin(string $accessor)
{
if (!isset($this->plugins[$accessor])) {
throw new PluginNotFoundException(
"Plugin with accessor, {$accessor} not found"
);
}
return $this->plugins[$accessor];
}
}