<?php
/**
 * 阿里Oss
 */
namespace upload\driver;
use JohnLui\AliyunOSS;
use Exception;

class OssDriver implements UploadInterface {

    protected $config = [
        'isInternal'  =>  false,  //是否允许公共上传
        'city'        => '杭州',
        'networkType' => '经典网络', 
        'access_id'   => '',
        'secret_key'  => '',
        'bucket'      => '',
        'domain'      => ''
    ];
    protected $errorMsg = '';
    private   $ossClient;

    public function __construct($config = array()) {
        $this->config = array_merge($this->config,(array)$config['driverConfig']);
        if ($this->config['networkType'] == 'VPC' && !$this->config['isInternal']) {
            throw new Exception("VPC 网络下不提供外网上传、下载等功能");
        }
        //参数赋值
        $this->ossClient = AliyunOSS::boot(
            $this->config['city'],
            $this->config['networkType'],
            $this->config['isInternal'],
            $this->config['access_id'],
            $this->config['secret_key']
        );
    }

    public function rootPath($path) {
        if (empty($this->config['access_id']) || empty($this->config['secret_key']) || empty($this->config['bucket']) || empty($this->config['domain'])) {
            $this->errorMsg = '请先配置Oss上传参数！';
            return false;
        }
        return true;
    }

    public function checkPath($path) {
        return true;
    }

    public function saveFile($fileData) {
        $file        = curl_file_create(realpath($fileData['tmp_name']), $fileData['type'],$fileData['savename']);
        $filepath    = str_replace('\\','/',substr($fileData['savepath'],strlen(PATH_PUBLIC)));
        $object_name = $filepath.$fileData['savename'];
        $this->ossClient->setBucket($this->config['bucket']);
        $header = [
            'ContentType' => $file->mime,
        ];
        try {
            $rel = $this->ossClient->uploadFile($object_name,$file->name,$header);
        }catch (\Exception $e) {
            $this->errorMsg = 'OSS上传失败';
            return false;
        }
        $rel = $this->ossClient->getPublicUrl($object_name);
        return ['ossurl' => $rel,'url' => $this->config['domain'].$object_name,'savepath'=> $this->config['domain'].$filepath,'savename' =>$fileData['savename']];
    }

    public function getError() {
        return $this->errorMsg;
    }
}