PluggableTrait.php 2.2 KB

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