| 1 |
<?php |
| 2 |
|
| 3 |
namespace League\Flysystem\Plugin; |
| 4 |
|
| 5 |
use BadMethodCallException; |
| 6 |
use League\Flysystem\FilesystemInterface; |
| 7 |
use League\Flysystem\PluginInterface; |
| 8 |
use LogicException; |
| 9 |
|
| 10 |
trait PluggableTrait |
| 11 |
{ |
| 12 |
/** |
| 13 |
* @var array |
| 14 |
*/ |
| 15 |
protected $plugins = []; |
| 16 |
|
| 17 |
/** |
| 18 |
* Register a plugin. |
| 19 |
* |
| 20 |
* @param PluginInterface $plugin |
| 21 |
* |
| 22 |
* @throws LogicException |
| 23 |
* |
| 24 |
* @return $this |
| 25 |
*/ |
| 26 |
public function addPlugin(PluginInterface $plugin) |
| 27 |
{ |
| 28 |
if ( ! method_exists($plugin, 'handle')) { |
| 29 |
throw new LogicException(get_class($plugin) . ' does not have a handle method.'); |
| 30 |
} |
| 31 |
|
| 32 |
$this->plugins[$plugin->getMethod()] = $plugin; |
| 33 |
|
| 34 |
return $this; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Find a specific plugin. |
| 39 |
* |
| 40 |
* @param string $method |
| 41 |
* |
| 42 |
* @throws PluginNotFoundException |
| 43 |
* |
| 44 |
* @return PluginInterface |
| 45 |
*/ |
| 46 |
protected function findPlugin($method) |
| 47 |
{ |
| 48 |
if ( ! isset($this->plugins[$method])) { |
| 49 |
throw new PluginNotFoundException('Plugin not found for method: ' . $method); |
| 50 |
} |
| 51 |
|
| 52 |
return $this->plugins[$method]; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Invoke a plugin by method name. |
| 57 |
* |
| 58 |
* @param string $method |
| 59 |
* @param array $arguments |
| 60 |
* @param FilesystemInterface $filesystem |
| 61 |
* |
| 62 |
* @throws PluginNotFoundException |
| 63 |
* |
| 64 |
* @return mixed |
| 65 |
*/ |
| 66 |
protected function invokePlugin($method, array $arguments, FilesystemInterface $filesystem) |
| 67 |
{ |
| 68 |
$plugin = $this->findPlugin($method); |
| 69 |
$plugin->setFilesystem($filesystem); |
| 70 |
$callback = [$plugin, 'handle']; |
| 71 |
|
| 72 |
return call_user_func_array($callback, $arguments); |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* Plugins pass-through. |
| 77 |
* |
| 78 |
* @param string $method |
| 79 |
* @param array $arguments |
| 80 |
* |
| 81 |
* @throws BadMethodCallException |
| 82 |
* |
| 83 |
* @return mixed |
| 84 |
*/ |
| 85 |
public function __call($method, array $arguments) |
| 86 |
{ |
| 87 |
try { |
| 88 |
return $this->invokePlugin($method, $arguments, $this); |
| 89 |
} catch (PluginNotFoundException $e) { |
| 90 |
throw new BadMethodCallException( |
| 91 |
'Call to undefined method ' |
| 92 |
. get_class($this) |
| 93 |
. '::' . $method |
| 94 |
); |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
|