FilesystemManager.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: NODELOG
  5. * Date: 16/7/21
  6. * Time: 下午5:49
  7. */
  8. namespace common\modules\attachment\components;
  9. use common\modules\attachment\components\contracts\Factory;
  10. use common\modules\attachment\components\image\Processor;
  11. use Yii;
  12. use yii\base\Component;
  13. use yii\base\Exception;
  14. class FilesystemManager extends Component implements Factory
  15. {
  16. public $defaultDriver;
  17. /**
  18. * The array of resolved filesystem drivers.
  19. *
  20. * @var array
  21. */
  22. public $disks = [];
  23. /**
  24. * Get a filesystem instance.
  25. *
  26. * @param string $name
  27. * @return FilesystemAdapter
  28. */
  29. public function drive($name = null)
  30. {
  31. return $this->disk($name);
  32. }
  33. /**
  34. * Get a filesystem instance.
  35. *
  36. * @param string $name
  37. * @return FilesystemAdapter
  38. */
  39. public function disk($name = null)
  40. {
  41. $name = $name ?: $this->defaultDriver;
  42. return $this->disks[$name] = $this->get($name);
  43. }
  44. /**
  45. * @param $name
  46. * @return FilesystemAdapter
  47. * @throws Exception
  48. */
  49. protected function get($name)
  50. {
  51. if (isset($this->disks[$name])) {
  52. /**
  53. * @var $filesystem
  54. */
  55. $filesystem = $this->disks[$name];
  56. if (!$filesystem instanceof FilesystemAdapter) {
  57. $filesystem = new FilesystemAdapter(Yii::createObject($this->disks[$name]));
  58. }
  59. return $filesystem;
  60. }
  61. throw new Exception('未定义的文件存储');
  62. }
  63. public function getPath($url)
  64. {
  65. return rtrim(str_replace(Yii::getAlias('@storageUrl'), Yii::getAlias('@storagePath'), $url), '/');
  66. }
  67. public function __call($method, $parameters)
  68. {
  69. return call_user_func_array([$this->disk(), $method], $parameters);
  70. }
  71. }