Local.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\librarys\storage\drivers;
  8. use app\librarys\storage\exceptions\StorageException;
  9. use app\librarys\storage\helpers\UrlConverter;
  10. class Local extends BaseDriver
  11. {
  12. public function __construct($config = [])
  13. {
  14. parent::__construct($config);
  15. $this->setUrlCallback(new UrlConverter());
  16. }
  17. public function put($localFile, $saveTo)
  18. {
  19. $saveTo = \Yii::$app->basePath . '/' . $saveTo;
  20. $saveDir = dirname($saveTo);
  21. try {
  22. if (!is_dir($saveDir) && !mkdir($saveDir, 0777, true)) {
  23. return false;
  24. }
  25. if (!copy($localFile, $saveTo)) {
  26. return false;
  27. }
  28. } catch (\Exception $ex) {
  29. throw new StorageException($ex->getMessage());
  30. }
  31. $hostInfo = '';
  32. if (\Yii::$app instanceof \yii\web\Application){
  33. $hostInfo = \Yii::$app->request->hostInfo;
  34. }
  35. return $hostInfo . '/' . static::getRelativePath(\Yii::$app->basePath, $saveTo);
  36. }
  37. public static function getRelativePath($from, $to)
  38. {
  39. $from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
  40. $to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
  41. $from = str_replace('\\', '/', $from);
  42. $to = str_replace('\\', '/', $to);
  43. $from = explode('/', $from);
  44. $to = explode('/', $to);
  45. $relPath = $to;
  46. foreach ($from as $depth => $dir) {
  47. if (strcasecmp($dir, $to[$depth]) === 0) {
  48. array_shift($relPath);
  49. } else {
  50. $remaining = count($from) - $depth;
  51. if ($remaining > 1) {
  52. $padLength = (count($relPath) + $remaining - 1) * -1;
  53. $relPath = array_pad($relPath, $padLength, '..');
  54. break;
  55. } else {
  56. // $relPath[0] = './' . $relPath[0];
  57. }
  58. }
  59. }
  60. return implode('/', $relPath);
  61. }
  62. }