ServiceProviderOss.php 2.61 KB
<?php namespace Resource;

use OSS\Core\OssException;
use OSS\OssClient;

/**
 * Class ServiceProviderOss
 * @package resource
 */
class ServiceProviderOss extends ServiceProviderAbstract
{
    /**
     * @var OssClient
     */
    private $client;
    /**
     * @var
     */
    private $bucket;
    /**
     * @var
     */
    private $styleUrl;
    /**
     * @var
     */
    private $url;

    /**
     * ServiceProviderOss constructor.
     * @param $options
     */
    public function __construct($options)
    {
        $accessKeyId = $options['accessKeyId'];
        $accessKeySecret = $options['accessKeySecret'];
        $endpoint = $options['endpoint'];

        $this->bucket = $options['bucket'];
        $this->styleUrl = $options['styleUrl'];
        $this->url = $options['url'];

        try {
            $this->client= new OssClient($accessKeyId, $accessKeySecret, $endpoint ,true);
        } catch (OssException $e) {
            throw $e;
        }
    }

    /**
     * @param $path
     * @param $destPath
     * @return null
     */
    public function add($path, $destPath)
    {
        return $this->client->uploadFile($this->bucket, $destPath, $path);
    }

    /**
     * @param $path
     * @param null $style
     * @return string
     */
    public function getUrl($path, $style = null)
    {
        if ($style) {
            return $path ? $this->styleUrl . '/' . $path . '!' . $style : $this->styleUrl;
        } else {
            return $path ? $this->url . '/' . $path : $this->url;
        }
    }

    /**
     * @param $path
     */
    public function delete($path)
    {
        $this->client->deleteObject($this->bucket, $path);
    }

    /**
     * @param $oldPath
     * @param $newPath
     * @return bool|null
     */
    public function replace($oldPath, $newPath, $tmpPath)
    {
        // 这两个函数是否成功都返回null, By LCN
        $this->client->deleteObject($this->bucket, $oldPath);
        $this->client->uploadFile($this->bucket, $newPath, $tmpPath);
    }

    /**
     * @param $path
     * @return bool
     */
    public function exists($path)
    {
        return $this->client->doesObjectExist($this->bucket, $path);
    }

    /**
     * @param $path
     * @return bool
     */
    public function move($oldPath, $newPath)
    {
       $this->client->copyObject($this->bucket, $oldPath, $this->bucket, $newPath);
        $this->delete($oldPath);
    }

    /**
     * @param Array $paths
     */
    public function batchDelete($paths)
    {
        $this->client->deleteObjects($this->bucket, $paths);
    }

    public function getClient()
    {
        return $this->client;
    }
}