QiniuTarget.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2018-01-16 11:28
  7. */
  8. namespace feehi\cdn;
  9. use Qiniu\Auth;
  10. use Qiniu\Config;
  11. use Qiniu\Storage\BucketManager;
  12. use Qiniu\Storage\UploadManager;
  13. use Exception;
  14. class QiniuTarget extends TargetAbstract implements TargetInterface
  15. {
  16. public $accessKey;
  17. public $secretKey;
  18. public $bucket;
  19. /** @var BucketManager */
  20. protected $client;
  21. protected $lastError = null;
  22. public function init()
  23. {
  24. parent::init();
  25. if( empty($this->accessKey) ) throw new Exception("Qiniu accessKey cannot be blank");
  26. if( empty($this->secretKey) ) throw new Exception("Qiniu secretKey cannot be blank");
  27. $this->client = $this->getBucketManager();
  28. }
  29. public function upload($localFile, $destFile)
  30. {
  31. $token = $this->getAuth()->uploadToken($this->bucket);
  32. $uploadMgr = new UploadManager();
  33. list($ret, $err) = $uploadMgr->putFile($token, $destFile, $localFile);
  34. if ($err !== null) {
  35. $this->lastError = $err;
  36. return false;
  37. } else {
  38. return true;
  39. }
  40. }
  41. public function multiUpload($localFile, $destFile)
  42. {
  43. $this->upload($localFile, $destFile);
  44. }
  45. public function delete($destFile)
  46. {
  47. $err = $this->client->delete($this->bucket, $destFile);
  48. if ($err) {
  49. $this->lastError = $err;
  50. return false;
  51. }
  52. return true;
  53. }
  54. public function exists($destFile)
  55. {
  56. list($fileInfo, $err) = $this->client->stat($this->bucket, $destFile);
  57. if ($err) {
  58. return false;
  59. } else {
  60. return true;
  61. }
  62. }
  63. public function getAuth()
  64. {
  65. return new Auth($this->accessKey, $this->secretKey);
  66. }
  67. private function getBucketManager()
  68. {
  69. return new BucketManager($this->getAuth(), new Config());
  70. }
  71. }