PluggableTrait.php
2.2 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
<?php
namespace League\Flysystem\Plugin;
use BadMethodCallException;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\PluginInterface;
use LogicException;
trait PluggableTrait
{
/**
* @var array
*/
protected $plugins = [];
/**
* Register a plugin.
*
* @param PluginInterface $plugin
*
* @throws LogicException
*
* @return $this
*/
public function addPlugin(PluginInterface $plugin)
{
if ( ! method_exists($plugin, 'handle')) {
throw new LogicException(get_class($plugin) . ' does not have a handle method.');
}
$this->plugins[$plugin->getMethod()] = $plugin;
return $this;
}
/**
* Find a specific plugin.
*
* @param string $method
*
* @throws PluginNotFoundException
*
* @return PluginInterface
*/
protected function findPlugin($method)
{
if ( ! isset($this->plugins[$method])) {
throw new PluginNotFoundException('Plugin not found for method: ' . $method);
}
return $this->plugins[$method];
}
/**
* Invoke a plugin by method name.
*
* @param string $method
* @param array $arguments
* @param FilesystemInterface $filesystem
*
* @throws PluginNotFoundException
*
* @return mixed
*/
protected function invokePlugin($method, array $arguments, FilesystemInterface $filesystem)
{
$plugin = $this->findPlugin($method);
$plugin->setFilesystem($filesystem);
$callback = [$plugin, 'handle'];
return call_user_func_array($callback, $arguments);
}
/**
* Plugins pass-through.
*
* @param string $method
* @param array $arguments
*
* @throws BadMethodCallException
*
* @return mixed
*/
public function __call($method, array $arguments)
{
try {
return $this->invokePlugin($method, $arguments, $this);
} catch (PluginNotFoundException $e) {
throw new BadMethodCallException(
'Call to undefined method '
. get_class($this)
. '::' . $method
);
}
}
}