This commit is contained in:
mkm 2023-11-02 14:13:04 +08:00
parent f1218ae456
commit 69c16ed3a2
3666 changed files with 215925 additions and 142326 deletions

View File

@ -6,6 +6,7 @@ use crmeb\basic\BaseController;
use think\facade\Db;
use think\facade\Log;
use crmeb\services\UploadService;
use think\api\Client;
class ProductLibrary extends BaseController
{
@ -14,7 +15,7 @@ class ProductLibrary extends BaseController
{
[$page, $limit] = $this->getPage();
$param = $this->request->param();
$where=['is_del'=>0];
$where = ['is_del' => 0];
$list = Db::name('product_library')->where($where)->page($page)->limit($limit)->order('id desc')->select();
$count = Db::name('product_library')->count();
return app('json')->success(['list' => $list, 'count' => $count]);
@ -85,112 +86,74 @@ class ProductLibrary extends BaseController
}
}
public function caiji($code='')
public function caiji($code = '')
{
$url_host=$this->request->host();
if ($code=='') {
if ($code == '') {
return app('json')->fail('编码不能为空');
}
$host = "https://codequery.market.alicloudapi.com";
$path = "/querybarcode";
$method = "GET";
$appcode = "7d2824a6331244918c66830cf33d2c4e"; //开通服务后 买家中心-查看AppCode
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "code=".$code;
$bodys = "";
$url = $host . $path . "?" . $querys;
try{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
if (1 == strpos("$" . $host, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
$out_put = curl_exec($curl);
$client = new Client("b1eb52b9-0379-4c56-b795-47d90a73ca6a");
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$result = $client->barcodeQuery()
->withCode($code)
->request();
list($header, $body) = explode("\r\n\r\n", $out_put, 2);
if ($httpCode == 200) {
$param=json_decode($body,true)['result'];
$data['store_name'] = $param['goodsName'].' '.$param['spec'];
$data['store_info'] = '';
$data['keyword'] = '';
$data['bar_code'] = $param['code'];
$data['is_used'] = 1;
$data['status'] = 1;
$data['cate_id'] = 0;
$data['unit_name'] = '';
$data['price'] = 0;
$data['cost'] = 0;
$data['ot_price'] = 0;
$data['stock'] =9999999;
$data['create_time'] = date('Y-m-d H:i:s');
$data['images'] = '';
$data['slider_image'] = '';
if($param['img']!=''){
try {
if ($result['code'] == 0) {
$upload = UploadService::create();
$dir = 'def/' . date('Y-m-d');
$oss = $upload->to($dir)->stream(file_get_contents($param['img']));
$data['image'] = $oss->filePath;
$data['slider_image'] = $oss->filePath;
$data['images'] = $oss->filePath;
// $filename = basename($param['img']); // 获取文件名
// $destination = public_path('uploads').'img/' .date('Y-m-d').'/'. $filename; // 目标路径
// if(!is_dir(public_path('uploads').'img/' .date('Y-m-d'))){ //需要先判断文件夹是否存
// mkdir(public_path('uploads').'img/' .date('Y-m-d'),0777,true);
// }
// $data['image']='https://'.$url_host.'/uploads/img/'.date('Y-m-d').'/'. $filename;
// file_put_contents($destination, file_get_contents($param['img']));
}else{
$data['image'] = 'https://lihai001.oss-cn-chengdu.aliyuncs.com/uploads/20230130/00ebcfdf75684f5494c0193075055d1.png';
}
$res = Db::name('product_library')->insert($data);
if($res){
return app('json')->success('添加成功');
}else{
throw new \think\exception\ValidateException('添加失败');
}
} else {
if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
throw new \think\exception\ValidateException("参数错误");
} elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
throw new \think\exception\ValidateException("AppCode错误");
} elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
throw new \think\exception\ValidateException("请求的 Method、Path 或者环境错误");
} elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
throw new \think\exception\ValidateException("服务未被授权或URL和Path不正确");
} elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
throw new \think\exception\ValidateException("套餐包次数用完");
} elseif ($httpCode == 403 && strpos($header, "Api Market Subscription quota exhausted") !== false) {
throw new \think\exception\ValidateException("套餐包次数用完,请续购套餐");
} elseif ($httpCode == 500) {
throw new \think\exception\ValidateException("API网关错误");
} elseif ($httpCode == 0) {
throw new \think\exception\ValidateException("URL错误");
} else {
$headers = explode("\r\n", $header);
$headList = array();
foreach ($headers as $head) {
$value = explode(':', $head);
$headList[$value[0]] = $value[1];
$param = $result['data'];
$data['store_name'] = $param['goodsName'];
$data['store_info'] = '';
$data['keyword'] = '';
$data['bar_code'] = $param['code'];
$data['is_used'] = 1;
$data['status'] = 1;
$data['cate_id'] = 0;
$data['unit_name'] = '';
$data['spec'] =$param['spec'];
$data['trademark'] =$param['trademark'];
$data['goods_type'] =$param['goodsType'];
$data['ycg'] =$param['ycg'];
$data['note'] =$param['note'];
$data['manu_address'] =$param['manuAddress'];
$data['price'] = $param['price']??0;
$data['cost'] = 0;
$data['ot_price'] = 0;
$data['stock'] = 9999999;
$data['create_time'] = date('Y-m-d H:i:s');
$data['images'] = '';
if ($param['sptmImg'] != '') {
$oss = $upload->to($dir)->stream(file_get_contents($param['sptmImg']));
$data['image'] = $oss->filePath;
} else {
$data['image'] = 'https://lihai001.oss-cn-chengdu.aliyuncs.com/uploads/20230130/00ebcfdf75684f5494c0193075055d1.png';
$data['slider_image'] = 'https://lihai001.oss-cn-chengdu.aliyuncs.com/uploads/20230130/00ebcfdf75684f5494c0193075055d1.png';
}
Log::error('商品采集错误:'.$headList['x-ca-error-message']);
throw new \think\exception\ValidateException("参数名错误 或 其他错误");
$arr=[];
foreach($param['imgList'] as $k=>$v){
$arr[] = $upload->to($dir)->stream(file_get_contents($v));
}
if(count($arr)>0){
$data['slider_image'] =implode(',',$arr);
}else{
$data['slider_image']='';
}
$data['images'] = '';
$res = Db::name('product_library')->insert($data);
if ($res) {
return app('json')->success('添加成功');
} else {
throw new \think\exception\ValidateException('添加失败');
}
} else {
Log::error('商品采集错误:' . $result['message']);
throw new \think\exception\ValidateException($result['message']);
}
} catch (\Exception $e) {
throw new \think\exception\ValidateException($e->getMessage());
}
}catch(\Exception $e){
throw new \think\exception\ValidateException($e->getMessage());
}
}
}

View File

@ -57,7 +57,9 @@
"fastknife/ajcaptcha": "^1.1",
"vlucas/phpdotenv": "^5.3",
"overtrue/pinyin": "4.1.0",
"jpush/jpush": "^3.6"
"jpush/jpush": "^3.6",
"guzzlehttp/guzzle": "^6.5",
"topthink/think-api": "1.0.27"
},
"require-dev": {
"symfony/var-dumper": "^4.2",

3455
composer.lock generated

File diff suppressed because it is too large Load Diff

BIN
composer.phar Normal file

Binary file not shown.

View File

@ -11,12 +11,12 @@
}
],
"require": {
"php": ">=5.5",
"php": "^5.5 || ^7.0 || ^8.0",
"ext-json": "*"
},
"require-dev": {
"phpunit/phpunit": "^4.0|^5.0|^6.0",
"squizlabs/php_codesniffer": "^3.0"
"phpunit/phpunit": "^4.8|^5.7|^6.6|^7.5|^8.5|^9.5",
"squizlabs/php_codesniffer": "^3.6"
},
"autoload": {
"files": [

View File

@ -29,14 +29,25 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
*/
protected $items = [];
/**
* The delimiter (alternative to a '.') to be used.
*
* @var string
*/
protected $delimiter = '.';
/**
* Create a new Dot instance
*
* @param mixed $items
* @param string $delimiter
*/
public function __construct($items = [])
public function __construct($items = [], $delimiter = '.')
{
$this->items = $this->getArrayItems($items);
$this->delimiter = strlen($delimiter) ? $delimiter : '.';
}
/**
@ -104,7 +115,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
}
$items = &$this->items;
$segments = explode('.', $key);
$segments = explode($this->delimiter, $key);
$lastSegment = array_pop($segments);
foreach ($segments as $segment) {
@ -148,6 +159,10 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
$items = $this->items;
}
if (!func_num_args()) {
$delimiter = $this->delimiter;
}
foreach ($items as $key => $value) {
if (is_array($value) && !empty($value)) {
$flatten = array_merge(
@ -179,13 +194,13 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
return $this->items[$key];
}
if (strpos($key, '.') === false) {
if (strpos($key, $this->delimiter) === false) {
return $default;
}
$items = $this->items;
foreach (explode('.', $key) as $segment) {
foreach (explode($this->delimiter, $key) as $segment) {
if (!is_array($items) || !$this->exists($items, $segment)) {
return $default;
}
@ -234,7 +249,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
continue;
}
foreach (explode('.', $key) as $segment) {
foreach (explode($this->delimiter, $key) as $segment) {
if (!is_array($items) || !$this->exists($items, $segment)) {
return false;
}
@ -446,7 +461,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
$items = &$this->items;
foreach (explode('.', $keys) as $key) {
foreach (explode($this->delimiter, $keys) as $key) {
if (!isset($items[$key]) || !is_array($items[$key])) {
$items[$key] = [];
}
@ -507,6 +522,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
* @param int|string $key
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($key)
{
return $this->has($key);
@ -518,6 +534,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
* @param int|string $key
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($key)
{
return $this->get($key);
@ -529,6 +546,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
* @param int|string|null $key
* @param mixed $value
*/
#[\ReturnTypeWillChange]
public function offsetSet($key, $value)
{
if (is_null($key)) {
@ -545,6 +563,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
*
* @param int|string $key
*/
#[\ReturnTypeWillChange]
public function offsetUnset($key)
{
$this->delete($key);
@ -562,6 +581,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
* @param int|string|null $key
* @return int
*/
#[\ReturnTypeWillChange]
public function count($key = null)
{
return count($this->get($key));
@ -578,6 +598,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
*
* @return \ArrayIterator
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator($this->items);
@ -594,6 +615,7 @@ class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
*
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->items;

View File

@ -11,13 +11,14 @@ use Adbar\Dot;
if (! function_exists('dot')) {
/**
* Create a new Dot object with the given items
* Create a new Dot object with the given items and optional delimiter
*
* @param mixed $items
* @param mixed $items
* @param string $delimiter
* @return \Adbar\Dot
*/
function dot($items)
function dot($items, $delimiter = '.')
{
return new Dot($items);
return new Dot($items, $delimiter);
}
}

View File

@ -149,7 +149,7 @@ $rsaKeyPair->getPrivateKey();
use AlibabaCloud\Credentials\Credential;
$bearerToken = new Credential([
'type' => 'bearer_token',
'type' => 'bearer',
'bearer_token' => '<bearer_token>',
]);
$bearerToken->getBearerToken();

View File

@ -150,7 +150,7 @@ If credential is required by the Cloud Call Centre (CCC), please apply for Beare
use AlibabaCloud\Credentials\Credential;
$bearerToken = new Credential([
'type' => 'bearer_token',
'type' => 'bearer',
'bearer_token' => '<bearer_token>',
]);
$bearerToken->getBearerToken();

View File

@ -47,7 +47,7 @@
"ext-sockets": "*",
"drupal/coder": "^8.3",
"symfony/dotenv": "^3.4",
"phpunit/phpunit": "^4.8.35|^5.4.3",
"phpunit/phpunit": "^5.7|^6.6|^7.5",
"monolog/monolog": "^1.24",
"composer/composer": "^1.8",
"mikey179/vfsstream": "^1.6",
@ -68,7 +68,10 @@
},
"config": {
"preferred-install": "dist",
"optimize-autoloader": true
"optimize-autoloader": true,
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
},
"minimum-stability": "dev",
"prefer-stable": true,

View File

@ -18,13 +18,13 @@ class BearerTokenCredential implements CredentialsInterface
/**
* BearerTokenCredential constructor.
*
* @param $bearerToken
* @param $bearer_token
*/
public function __construct($bearerToken)
public function __construct($bearer_token)
{
Filter::bearerToken($bearerToken);
Filter::bearerToken($bearer_token);
$this->bearerToken = $bearerToken;
$this->bearerToken = $bearer_token;
}
/**

View File

@ -35,6 +35,7 @@ class Credential
'ecs_ram_role' => EcsRamRoleCredential::class,
'ram_role_arn' => RamRoleArnCredential::class,
'rsa_key_pair' => RsaKeyPairCredential::class,
'bearer' => BearerTokenCredential::class,
];
/**

View File

@ -35,11 +35,11 @@ class Filter
public static function bearerToken($bearerToken)
{
if (!is_string($bearerToken)) {
throw new InvalidArgumentException('Bearer Token must be a string');
throw new InvalidArgumentException('bearer_token must be a string');
}
if ($bearerToken === '') {
throw new InvalidArgumentException('Bearer Token cannot be empty');
throw new InvalidArgumentException('bearer_token cannot be empty');
}
return $bearerToken;

View File

@ -11,10 +11,11 @@
],
"require": {
"php": ">5.5",
"alibabacloud/tea-utils": "^0.2.0",
"alibabacloud/tea-utils": "^0.2.17",
"alibabacloud/credentials": "^1.1",
"alibabacloud/openapi-util": "^0.1.10",
"alibabacloud/gateway-spi": "^0.0.1"
"alibabacloud/openapi-util": "^0.1.10|^0.2.1",
"alibabacloud/gateway-spi": "^1",
"alibabacloud/tea-xml": "^0.2"
},
"autoload": {
"psr-4": {

View File

@ -1,14 +1,15 @@
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace Darabonba\OpenApi\Models;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\Tea\Model;
use AlibabaCloud\Credentials\Credential;
use Darabonba\OpenApi\Models\GlobalParameters;
/**
* Model for initing client.
* Model for initing client
*/
class Config extends Model
{
@ -37,12 +38,13 @@ class Config extends Model
'type' => '',
'signatureVersion' => '',
'signatureAlgorithm' => '',
'key' => '',
'cert' => '',
'ca' => '',
];
public function validate()
{
}
public function toMap()
{
$res = [];
@ -118,13 +120,22 @@ class Config extends Model
if (null !== $this->signatureAlgorithm) {
$res['signatureAlgorithm'] = $this->signatureAlgorithm;
}
if (null !== $this->globalParameters) {
$res['globalParameters'] = null !== $this->globalParameters ? $this->globalParameters->toMap() : null;
}
if (null !== $this->key) {
$res['key'] = $this->key;
}
if (null !== $this->cert) {
$res['cert'] = $this->cert;
}
if (null !== $this->ca) {
$res['ca'] = $this->ca;
}
return $res;
}
/**
* @param array $map
*
* @return Config
*/
public static function fromMap($map = [])
@ -202,219 +213,212 @@ class Config extends Model
if (isset($map['signatureAlgorithm'])) {
$model->signatureAlgorithm = $map['signatureAlgorithm'];
}
if (isset($map['globalParameters'])) {
$model->globalParameters = GlobalParameters::fromMap($map['globalParameters']);
}
if (isset($map['key'])) {
$model->key = $map['key'];
}
if (isset($map['cert'])) {
$model->cert = $map['cert'];
}
if (isset($map['ca'])) {
$model->ca = $map['ca'];
}
return $model;
}
/**
* @description accesskey id
*
* @var string
*/
public $accessKeyId;
/**
* @description accesskey secret
*
* @var string
*/
public $accessKeySecret;
/**
* @description security token
*
* @example a.txt
*
* @var string
*/
public $securityToken;
/**
* @description http protocol
*
* @example http
*
* @var string
*/
public $protocol;
/**
* @description http method
*
* @example GET
*
* @var string
*/
public $method;
/**
* @description region id
*
* @example cn-hangzhou
*
* @var string
*/
public $regionId;
/**
* @description read timeout
*
* @example 10
*
* @var int
*/
public $readTimeout;
/**
* @description connect timeout
*
* @example 10
*
* @var int
*/
public $connectTimeout;
/**
* @description http proxy
*
* @example http://localhost
*
* @var string
*/
public $httpProxy;
/**
* @description https proxy
*
* @example https://localhost
*
* @var string
*/
public $httpsProxy;
/**
* @description credential
*
* @example
*
* @example
* @var Credential
*/
public $credential;
/**
* @description endpoint
*
* @example cs.aliyuncs.com
*
* @var string
*/
public $endpoint;
/**
* @description proxy white list
*
* @example http://localhost
*
* @var string
*/
public $noProxy;
/**
* @description max idle conns
*
* @example 3
*
* @var int
*/
public $maxIdleConns;
/**
* @description network for endpoint
*
* @example public
*
* @var string
*/
public $network;
/**
* @description user agent
*
* @example Alibabacloud/1
*
* @var string
*/
public $userAgent;
/**
* @description suffix for endpoint
*
* @example aliyun
*
* @var string
*/
public $suffix;
/**
* @description socks5 proxy
*
* @var string
*/
public $socks5Proxy;
/**
* @description socks5 network
*
* @example TCP
*
* @var string
*/
public $socks5NetWork;
/**
* @description endpoint type
*
* @example internal
*
* @var string
*/
public $endpointType;
/**
* @description OpenPlatform endpoint
*
* @example openplatform.aliyuncs.com
*
* @var string
*/
public $openPlatformEndpoint;
/**
* @description credential type
*
* @example access_key
*
* @deprecated
*
* @var string
*/
public $type;
/**
* @description Signature Version
*
* @example v1
*
* @var string
*/
public $signatureVersion;
/**
* @description Signature Algorithm
*
* @example ACS3-HMAC-SHA256
*
* @var string
*/
public $signatureAlgorithm;
/**
* @description Global Parameters
* @var GlobalParameters
*/
public $globalParameters;
/**
* @description privite key for client certificate
* @example MIIEvQ
* @var string
*/
public $key;
/**
* @description client certificate
* @example -----BEGIN CERTIFICATE-----
xxx-----END CERTIFICATE-----
* @var string
*/
public $cert;
/**
* @description server certificate
* @example -----BEGIN CERTIFICATE-----
xxx-----END CERTIFICATE-----
* @var string
*/
public $ca;
}

View File

@ -0,0 +1,42 @@
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace Darabonba\OpenApi\Models;
use AlibabaCloud\Tea\Model;
class GlobalParameters extends Model
{
public function validate()
{
}
public function toMap()
{
$res = [];
if (null !== $this->headers) {
$res['headers'] = $this->headers;
}
if (null !== $this->queries) {
$res['queries'] = $this->queries;
}
return $res;
}
/**
* @param array $map
* @return GlobalParameters
*/
public static function fromMap($map = [])
{
$model = new self();
if (isset($map['headers'])) {
$model->headers = $map['headers'];
}
if (isset($map['queries'])) {
$model->queries = $map['queries'];
}
return $model;
}
public $headers;
public $queries;
}

View File

@ -1,7 +1,6 @@
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace Darabonba\OpenApi\Models;
use AlibabaCloud\Tea\Model;
@ -11,7 +10,6 @@ class OpenApiRequest extends Model
public function validate()
{
}
public function toMap()
{
$res = [];
@ -30,13 +28,13 @@ class OpenApiRequest extends Model
if (null !== $this->hostMap) {
$res['hostMap'] = $this->hostMap;
}
if (null !== $this->endpointOverride) {
$res['endpointOverride'] = $this->endpointOverride;
}
return $res;
}
/**
* @param array $map
*
* @return OpenApiRequest
*/
public static function fromMap($map = [])
@ -57,10 +55,11 @@ class OpenApiRequest extends Model
if (isset($map['hostMap'])) {
$model->hostMap = $map['hostMap'];
}
if (isset($map['endpointOverride'])) {
$model->endpointOverride = $map['endpointOverride'];
}
return $model;
}
public $headers;
public $query;
@ -70,4 +69,6 @@ class OpenApiRequest extends Model
public $stream;
public $hostMap;
public $endpointOverride;
}

View File

@ -1,7 +1,6 @@
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace Darabonba\OpenApi\Models;
use AlibabaCloud\Tea\Model;
@ -19,7 +18,6 @@ class Params extends Model
Model::validateRequired('bodyType', $this->bodyType, true);
Model::validateRequired('reqBodyType', $this->reqBodyType, true);
}
public function toMap()
{
$res = [];
@ -50,13 +48,10 @@ class Params extends Model
if (null !== $this->style) {
$res['style'] = $this->style;
}
return $res;
}
/**
* @param array $map
*
* @return Params
*/
public static function fromMap($map = [])
@ -89,10 +84,8 @@ class Params extends Model
if (isset($map['style'])) {
$model->style = $map['style'];
}
return $model;
}
/**
* @var string
*/

File diff suppressed because it is too large Load Diff

View File

@ -9,6 +9,8 @@ use Darabonba\GatewaySpi\Models\InterceptorContext;
use Darabonba\GatewaySpi\Models\AttributeMap;
abstract class Client {
public function __construct(){
}
/**
* @param InterceptorContext $context

View File

@ -16,7 +16,7 @@
"lizhichao/one-sm": "^1.5"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35|^5.4.3"
"phpunit/phpunit": "*"
},
"autoload": {
"psr-4": {

View File

@ -8,7 +8,7 @@
<directory>tests</directory>
</testsuite>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>

View File

@ -160,26 +160,26 @@ class OpenApiUtilClient
}
/**
* Parse array into a string with specified style.
* Parse object into a string with specified style.
*
* @style specified style e.g. repeatList
*
* @param mixed $array the array
* @param mixed $object the object
* @param string $prefix the prefix string
* @param string $style
*
* @return string the string
*/
public static function arrayToStringWithSpecifiedStyle($array, $prefix, $style)
public static function arrayToStringWithSpecifiedStyle($object, $prefix, $style)
{
if (null === $array) {
if (null === $object) {
return '';
}
if ('repeatList' === $style) {
return self::toForm([$prefix => $array]);
return self::toForm([$prefix => $object]);
}
if ('simple' == $style || 'spaceDelimited' == $style || 'pipeDelimited' == $style) {
$strs = self::flatten($array);
$strs = self::flatten($object);
switch ($style) {
case 'spaceDelimited':
@ -192,7 +192,8 @@ class OpenApiUtilClient
return implode(',', $strs);
}
} elseif ('json' === $style) {
return json_encode($array);
self::parse($object, $parsed);
return json_encode($parsed);
}
return '';
@ -423,7 +424,7 @@ class OpenApiUtilClient
foreach ($items as $key => $value) {
$pos = \is_int($key) ? $key + 1 : $key;
if ($value instanceof Model) {
$value = $value->toMap();
} elseif (\is_object($value)) {
@ -436,6 +437,9 @@ class OpenApiUtilClient
self::flatten($value, $delimiter, $prepend . $pos . $delimiter)
);
} else {
if (\is_bool($value)) {
$value = true === $value ? 'true' : 'false';
}
$flatten[$prepend . $pos] = $value;
}
}

View File

@ -63,12 +63,14 @@ class OpenApiUtilClientTest extends TestCase
public function testToForm()
{
$this->assertEquals('client=test&strs.1=str1&strs.2=str2&tag.key=value', OpenApiUtilClient::toForm([
$this->assertEquals('bool=true&client=test&strs.1=str1&strs.2=str2&strs.3=false&tag.key=value', OpenApiUtilClient::toForm([
'client' => 'test',
'tag' => [
'key' => 'value',
],
'strs' => ['str1', 'str2'],
'strs' => ['str1', 'str2', false],
'bool' => true,
'null' => null,
]));
}
@ -83,6 +85,7 @@ class OpenApiUtilClientTest extends TestCase
$model = new MockModel();
$model->a = 'foo';
$model->c = 'boo';
$model->r = true;
$array = [
'a' => 'a',
@ -95,7 +98,9 @@ class OpenApiUtilClientTest extends TestCase
'c' => ['x', 'y', 'z'],
'd' => [
$model
]
],
'e' => true,
'f' => null,
];
$this->assertEquals([
'a' => 'a',
@ -107,6 +112,10 @@ class OpenApiUtilClientTest extends TestCase
'd.1.A' => 'foo',
'd.1.b' => '',
'd.1.c' => 'boo',
'd.1.c' => 'boo',
'd.1.r' => 'true',
'e' => 'true',
'f' => null
], OpenApiUtilClient::query($array));
}
@ -142,6 +151,48 @@ class OpenApiUtilClientTest extends TestCase
)
);
$test = new ParseModel([
'str' => 'A',
'model' => new ParseModel(['str' => 'sub model']),
'array' => [1, 2, 3],
]);
$this->assertEquals(
'{"str":"A","model":{"str":"sub model","model":null,"array":null},"array":[1,2,3]}',
OpenApiUtilClient::arrayToStringWithSpecifiedStyle(
$test,
'instance',
'json'
)
);
// model item in array
$test = [
new ParseModel([
'str' => 'A',
]),
];
$this->assertEquals(
'[{"str":"A","model":null,"array":null}]',
OpenApiUtilClient::arrayToStringWithSpecifiedStyle(
$test,
'instance',
'json'
)
);
// model item in map
$test = [
'model' => new ParseModel([
'str' => 'A',
]),
];
$this->assertEquals(
'{"model":{"str":"A","model":null,"array":null}}',
OpenApiUtilClient::arrayToStringWithSpecifiedStyle(
$test,
'instance',
'json'
)
);
$this->assertEquals(
'ok,test,2,3',
OpenApiUtilClient::arrayToStringWithSpecifiedStyle(
@ -295,7 +346,8 @@ class OpenApiUtilClientTest extends TestCase
'b9ff646822f41ef647c1416fa2b8408923828abc0464af6706e18db3e8553da8',
OpenApiUtilClient::hexEncode(OpenApiUtilClient::sign('secret', 'source', 'ACS3-HMAC-SM3'))
);
$this->assertEquals('1d93c62698a1c26427265668e79fac099aa26c1df873669599a2fb2f272e64c9',
$this->assertEquals(
'1d93c62698a1c26427265668e79fac099aa26c1df873669599a2fb2f272e64c9',
OpenApiUtilClient::hexEncode(OpenApiUtilClient::sign('secret', 'source', 'ACS3-HMAC-SHA256'))
);
}
@ -311,14 +363,14 @@ class OpenApiUtilClientTest extends TestCase
'array' => [1, 2, 3],
]),
[ // model item in array
new ParseModel([
'str' => 'A',
]),
new ParseModel([
'str' => 'A',
]),
],
[ // model item in map
'model' => new ParseModel([
'str' => 'A',
]),
'model' => new ParseModel([
'str' => 'A',
]),
],
],
'expected' => [
@ -347,6 +399,12 @@ class OpenApiUtilClientTest extends TestCase
],
],
],
'expectedJsonStr' => [
'["NotArray"]',
'NotArray',
'NotArray',
'NotArray',
],
];
}
}

View File

@ -1,15 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false" backupStaticAttributes="false" bootstrap="tests/bootstrap.php" colors="true"
convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true"
executionOrder="depends,defects" processIsolation="false" stopOnFailure="false">
<logging>
<log type="coverage-html" target="cache/coverage" lowUpperBound="35" highLowerBound="70"/>
<log type="coverage-clover" target="cache/coverage.clover"/>
</logging>
<testsuites>
<testsuite name="default">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" bootstrap="tests/bootstrap.php" colors="true" executionOrder="depends,defects" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.0/phpunit.xsd" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
<report>
<clover outputFile="cache/coverage.clover"/>
<html outputDirectory="cache/coverage" lowUpperBound="35" highLowerBound="70"/>
</report>
</coverage>
<logging/>
<testsuites>
<testsuite name="default">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@ -19,6 +19,9 @@ class Utils
*/
public static function toBytes($string)
{
if (self::is_bytes($string)) {
return $string;
}
$bytes = [];
for ($i = 0; $i < \strlen($string); ++$i) {
$bytes[] = \ord($string[$i]);
@ -36,6 +39,9 @@ class Utils
*/
public static function toString($bytes)
{
if (\is_string($bytes)) {
return $bytes;
}
$str = '';
foreach ($bytes as $ch) {
$str .= \chr($ch);
@ -177,15 +183,15 @@ class Utils
*/
public static function toJSONString($object)
{
if (null === $object) {
$object = new \stdClass();
if (is_string($object)) {
return $object;
}
if ($object instanceof Model) {
$object = $object->toMap();
}
return json_encode($object);
return json_encode($object, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
}
/**
@ -314,7 +320,11 @@ class Utils
*/
public static function assertAsBoolean($value)
{
return \is_bool($value);
if (\is_bool($value)) {
return $value;
}
throw new \InvalidArgumentException('It is not a boolean value.');
}
/**
@ -322,21 +332,18 @@ class Utils
*
* @param mixed $value
*
* @return bool the string value
* @return string the string value
*/
public static function assertAsString($value)
{
return \is_string($value);
if (\is_string($value)) {
return $value;
}
throw new \InvalidArgumentException('It is not a string value.');
}
/**
* Assert a value, if it is a bytes, return it, otherwise throws.
*
* @param mixed $value
*
* @return bool the bytes value
*/
public static function assertAsBytes($value)
private static function is_bytes($value)
{
if (!\is_array($value)) {
return false;
@ -358,16 +365,49 @@ class Utils
return true;
}
/**
* Assert a value, if it is a bytes, return it, otherwise throws.
*
* @param mixed $value
*
* @return bytes the bytes value
*/
public static function assertAsBytes($value)
{
if (self::is_bytes($value)) {
return $value;
}
throw new \InvalidArgumentException('It is not a bytes value.');
}
/**
* Assert a value, if it is a number, return it, otherwise throws.
*
* @param mixed $value
*
* @return bool the number value
* @return int the number value
*/
public static function assertAsNumber($value)
{
return is_numeric($value);
if (\is_numeric($value)) {
return $value;
}
throw new \InvalidArgumentException('It is not a number value.');
}
/**
* Assert a value, if it is a integer, return it, otherwise throws
* @param mixed $value
* @return int the integer value
*/
public static function assertAsInteger($value){
if (\is_int($value)) {
return $value;
}
throw new \InvalidArgumentException('It is not a int value.');
}
/**

View File

@ -1,39 +1,261 @@
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Model;
class RuntimeOptions extends Model
{
/**
* The common runtime options model
*/
class RuntimeOptions extends Model {
protected $_name = [
'autoretry' => 'autoretry',
'ignoreSSL' => 'ignoreSSL',
'key' => 'key',
'cert' => 'cert',
'ca' => 'ca',
'maxAttempts' => 'max_attempts',
'backoffPolicy' => 'backoff_policy',
'backoffPeriod' => 'backoff_period',
'readTimeout' => 'readTimeout',
'connectTimeout' => 'connectTimeout',
'httpProxy' => 'httpProxy',
'httpsProxy' => 'httpsProxy',
'noProxy' => 'noProxy',
'maxIdleConns' => 'maxIdleConns',
'localAddr' => 'localAddr',
'socks5Proxy' => 'socks5Proxy',
'socks5NetWork' => 'socks5NetWork',
'keepAlive' => 'keepAlive',
];
public function validate() {}
public function toMap() {
$res = [];
if (null !== $this->autoretry) {
$res['autoretry'] = $this->autoretry;
}
if (null !== $this->ignoreSSL) {
$res['ignoreSSL'] = $this->ignoreSSL;
}
if (null !== $this->key) {
$res['key'] = $this->key;
}
if (null !== $this->cert) {
$res['cert'] = $this->cert;
}
if (null !== $this->ca) {
$res['ca'] = $this->ca;
}
if (null !== $this->maxAttempts) {
$res['max_attempts'] = $this->maxAttempts;
}
if (null !== $this->backoffPolicy) {
$res['backoff_policy'] = $this->backoffPolicy;
}
if (null !== $this->backoffPeriod) {
$res['backoff_period'] = $this->backoffPeriod;
}
if (null !== $this->readTimeout) {
$res['readTimeout'] = $this->readTimeout;
}
if (null !== $this->connectTimeout) {
$res['connectTimeout'] = $this->connectTimeout;
}
if (null !== $this->httpProxy) {
$res['httpProxy'] = $this->httpProxy;
}
if (null !== $this->httpsProxy) {
$res['httpsProxy'] = $this->httpsProxy;
}
if (null !== $this->noProxy) {
$res['noProxy'] = $this->noProxy;
}
if (null !== $this->maxIdleConns) {
$res['maxIdleConns'] = $this->maxIdleConns;
}
if (null !== $this->localAddr) {
$res['localAddr'] = $this->localAddr;
}
if (null !== $this->socks5Proxy) {
$res['socks5Proxy'] = $this->socks5Proxy;
}
if (null !== $this->socks5NetWork) {
$res['socks5NetWork'] = $this->socks5NetWork;
}
if (null !== $this->keepAlive) {
$res['keepAlive'] = $this->keepAlive;
}
return $res;
}
/**
* @param array $map
* @return RuntimeOptions
*/
public static function fromMap($map = []) {
$model = new self();
if(isset($map['autoretry'])){
$model->autoretry = $map['autoretry'];
}
if(isset($map['ignoreSSL'])){
$model->ignoreSSL = $map['ignoreSSL'];
}
if(isset($map['key'])){
$model->key = $map['key'];
}
if(isset($map['cert'])){
$model->cert = $map['cert'];
}
if(isset($map['ca'])){
$model->ca = $map['ca'];
}
if(isset($map['max_attempts'])){
$model->maxAttempts = $map['max_attempts'];
}
if(isset($map['backoff_policy'])){
$model->backoffPolicy = $map['backoff_policy'];
}
if(isset($map['backoff_period'])){
$model->backoffPeriod = $map['backoff_period'];
}
if(isset($map['readTimeout'])){
$model->readTimeout = $map['readTimeout'];
}
if(isset($map['connectTimeout'])){
$model->connectTimeout = $map['connectTimeout'];
}
if(isset($map['httpProxy'])){
$model->httpProxy = $map['httpProxy'];
}
if(isset($map['httpsProxy'])){
$model->httpsProxy = $map['httpsProxy'];
}
if(isset($map['noProxy'])){
$model->noProxy = $map['noProxy'];
}
if(isset($map['maxIdleConns'])){
$model->maxIdleConns = $map['maxIdleConns'];
}
if(isset($map['localAddr'])){
$model->localAddr = $map['localAddr'];
}
if(isset($map['socks5Proxy'])){
$model->socks5Proxy = $map['socks5Proxy'];
}
if(isset($map['socks5NetWork'])){
$model->socks5NetWork = $map['socks5NetWork'];
}
if(isset($map['keepAlive'])){
$model->keepAlive = $map['keepAlive'];
}
return $model;
}
/**
* @description whether to try again
* @var bool
*/
public $autoretry;
/**
* @description ignore SSL validation
* @var bool
*/
public $ignoreSSL;
/**
* @description privite key for client certificate
* @var string
*/
public $key;
/**
* @description client certificate
* @var string
*/
public $cert;
/**
* @description server certificate
* @var string
*/
public $ca;
/**
* @description maximum number of retries
* @var int
*/
public $maxAttempts;
/**
* @description backoff policy
* @var string
*/
public $backoffPolicy;
/**
* @description backoff period
* @var int
*/
public $backoffPeriod;
/**
* @description read timeout
* @var int
*/
public $readTimeout;
/**
* @description connect timeout
* @var int
*/
public $connectTimeout;
/**
* @description http proxy url
* @var string
*/
public $httpProxy;
/**
* @description https Proxy url
* @var string
*/
public $httpsProxy;
/**
* @description agent blacklist
* @var string
*/
public $noProxy;
/**
* @description maximum number of connections
* @var int
*/
public $maxIdleConns;
/**
* @description local addr
* @var string
*/
public $localAddr;
/**
* @description SOCKS5 proxy
* @var string
*/
public $socks5Proxy;
/**
* @description SOCKS5 netWork
* @var string
*/
public $socks5NetWork;
protected $_name = [];
/**
* @description whether to enable keep-alive
* @var bool
*/
public $keepAlive;
}

View File

@ -4,6 +4,7 @@ namespace AlibabaCloud\Tea\Utils\Tests;
use AlibabaCloud\Tea\Model;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\StreamInterface;
@ -24,6 +25,11 @@ final class UtilsTest extends TestCase
$this->assertEquals([
115, 116, 114, 105, 110, 103,
], Utils::toBytes('string'));
$this->assertEquals([
115, 116, 114, 105, 110, 103,
], Utils::toBytes([
115, 116, 114, 105, 110, 103,
]));
}
public function testToString()
@ -31,6 +37,7 @@ final class UtilsTest extends TestCase
$this->assertEquals('string', Utils::toString([
115, 116, 114, 105, 110, 103,
]));
$this->assertEquals('string', Utils::toString('string'));
}
public function testParseJSON()
@ -106,6 +113,22 @@ final class UtilsTest extends TestCase
{
$object = new \stdClass();
$this->assertJson(Utils::toJSONString($object));
$this->assertEquals('[]', Utils::toJSONString([]));
$this->assertEquals('["foo"]', Utils::toJSONString(['foo']));
$this->assertEquals(
'{"str":"test","number":1,"bool":false,"null":null,"chinese":"中文","http":"https://aliyun.com:8080/zh/中文.html"}',
Utils::toJSONString([
'str' => 'test',
'number' => 1,
'bool' => FALSE,
'null' => null,
'chinese' => '中文',
'http' => 'https://aliyun.com:8080/zh/中文.html',
])
);
$this->assertEquals('1', Utils::toJSONString(1));
$this->assertEquals('true', Utils::toJSONString(TRUE));
$this->assertEquals('null', Utils::toJSONString(null));
}
public function testEmpty()
@ -170,39 +193,88 @@ final class UtilsTest extends TestCase
public function testAssertAsBoolean()
{
$this->assertTrue(Utils::assertAsBoolean(true));
$this->assertFalse(Utils::assertAsBoolean('true'));
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('It is not a boolean value.');
Utils::assertAsBoolean('true');
try {
$map = true;
$this->assertEquals($map, Utils::assertAsBoolean($map));
} catch (\Exception $e) {
// should not be here
$this->assertTrue(false);
}
}
public function testAssertAsString()
{
$this->assertTrue(Utils::assertAsString('123'));
$this->assertFalse(Utils::assertAsString(123));
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('It is not a string value.');
Utils::assertAsString(123);
try {
$map = '123';
$this->assertEquals($map, Utils::assertAsString($map));
} catch (\Exception $e) {
// should not be here
$this->assertTrue(false);
}
}
public function testAssertAsBytes()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('It is not a bytes value.');
// failed because $var is not array
$this->assertFalse(Utils::assertAsBytes('test'));
Utils::assertAsBytes('test');
// failed because $var is map not array
$this->assertFalse(Utils::assertAsBytes(['foo' => 1]));
Utils::assertAsBytes(['foo' => 1]);
// failed because item value is not int
$this->assertFalse(Utils::assertAsBytes(['1']));
Utils::assertAsBytes(['1']);
// failed because item value is out off range
$this->assertFalse(Utils::assertAsBytes([256]));
Utils::assertAsBytes([256]);
// success
$this->assertTrue(Utils::assertAsBytes([1, 2, 3]));
$this->assertTrue(Utils::assertAsBytes(Utils::toBytes('string')));
try {
// success
$map = [1, 2, 3];
$this->assertEquals($map, Utils::assertAsBytes($map));
$this->assertEquals([
115, 116, 114, 105, 110, 103,
], Utils::assertAsBytes(Utils::toBytes('string')));
} catch (\Exception $e) {
// should not be here
$this->assertTrue(false);
}
}
public function testAssertAsNumber()
{
$this->assertTrue(Utils::assertAsNumber(123));
$this->assertFalse(Utils::assertAsNumber('string'));
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('It is not a number value.');
Utils::assertAsNumber('is not number');
try {
$map = 123;
$this->assertEquals($map, Utils::assertAsNumber($map));
} catch (\Exception $e) {
// should not be here
$this->assertTrue(false);
}
}
public function testAssertAsInteger()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('It is not a int value.');
Utils::assertAsInteger('is not int');
try {
$map = 123;
$this->assertEquals($map, Utils::assertAsInteger($map));
} catch (\Exception $e) {
// should not be here
$this->assertTrue(false);
}
}
public function testAssertAsMap()
@ -326,6 +398,42 @@ final class UtilsTest extends TestCase
Utils::assertAsReadable(0);
}
public function testRuntimeOptions()
{
$opts = new RuntimeOptions([
"autoretry" => false,
"ignoreSSL" => false,
"key" => "key",
"cert" => "cert",
"ca" => "ca",
"maxAttempts" => 3,
"backoffPolicy" => "backoffPolicy",
"backoffPeriod" => 10,
"readTimeout" => 3000,
"connectTimeout" => 3000,
"httpProxy" => "httpProxy",
"httpsProxy" => "httpsProxy",
"noProxy" => "noProxy",
"maxIdleConns" => 300,
"keepAlive" => true,
]);
$this->assertEquals(false, $opts->autoretry);
$this->assertEquals(false, $opts->ignoreSSL);
$this->assertEquals("key", $opts->key);
$this->assertEquals("cert", $opts->cert);
$this->assertEquals("ca", $opts->ca);
$this->assertEquals(3, $opts->maxAttempts);
$this->assertEquals("backoffPolicy", $opts->backoffPolicy);
$this->assertEquals(10, $opts->backoffPeriod);
$this->assertEquals(3000, $opts->readTimeout);
$this->assertEquals(3000, $opts->connectTimeout);
$this->assertEquals("httpProxy", $opts->httpProxy);
$this->assertEquals("httpsProxy", $opts->httpsProxy);
$this->assertEquals("noProxy", $opts->noProxy);
$this->assertEquals(300, $opts->maxIdleConns);
$this->assertEquals(true, $opts->keepAlive);
}
private function convert($body, &$content)
{
$class = new \ReflectionClass($body);

12
vendor/alibabacloud/tea-xml/.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
composer.phar
/vendor/
# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control
# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file
composer.lock
.idea
.DS_Store
cache/
*.cache

View File

@ -0,0 +1,65 @@
<?php
/*
* This document has been generated with
* https://mlocati.github.io/php-cs-fixer-configurator/#version:2.15|configurator
* you can change this configuration by importing this file.
*/
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setIndent(' ')
->setRules([
'@PSR2' => true,
'@PhpCsFixer' => true,
'@Symfony:risky' => true,
'concat_space' => ['spacing' => 'one'],
'array_syntax' => ['syntax' => 'short'],
'array_indentation' => true,
'combine_consecutive_unsets' => true,
'method_separation' => true,
'single_quote' => true,
'declare_equal_normalize' => true,
'function_typehint_space' => true,
'hash_to_slash_comment' => true,
'include' => true,
'lowercase_cast' => true,
'no_multiline_whitespace_before_semicolons' => true,
'no_leading_import_slash' => true,
'no_multiline_whitespace_around_double_arrow' => true,
'no_spaces_around_offset' => true,
'no_unneeded_control_parentheses' => true,
'no_unused_imports' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
'single_blank_line_before_namespace' => true,
'single_class_element_per_statement' => true,
'space_after_semicolon' => true,
'standardize_not_equals' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'whitespace_after_comma_in_array' => true,
'no_extra_consecutive_blank_lines' => [
'curly_brace_block',
'extra',
'parenthesis_brace_block',
'square_brace_block',
'throw',
'use',
],
'binary_operator_spaces' => [
'align_double_arrow' => true,
'align_equals' => true,
],
'braces' => [
'allow_single_line_closure' => true,
],
])
->setFinder(
PhpCsFixer\Finder::create()
->exclude('vendor')
->exclude('tests')
->in(__DIR__)
);

View File

@ -0,0 +1,31 @@
English | [简体中文](README-CN.md)
![](https://aliyunsdk-pages.alicdn.com/icons/AlibabaCloud.svg)
## Alibaba Cloud Tea XML Library for PHP
## Installation
### Composer
```bash
composer require alibabacloud/tea-xml
```
## Issues
[Opening an Issue](https://github.com/aliyun/tea-xml/issues/new), Issues not conforming to the guidelines may be closed immediately.
## Changelog
Detailed changes for each release are documented in the [release notes](./ChangeLog.txt).
## References
* [Latest Release](https://github.com/aliyun/tea-xml)
## License
[Apache-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.

31
vendor/alibabacloud/tea-xml/README.md vendored Normal file
View File

@ -0,0 +1,31 @@
[English](README.md) | 简体中文
![](https://aliyunsdk-pages.alicdn.com/icons/AlibabaCloud.svg)
## Alibaba Cloud Tea XML Library for PHP
## 安装
### Composer
```bash
composer require alibabacloud/tea-xml
```
## 问题
[提交 Issue](https://github.com/aliyun/tea-xml/issues/new),不符合指南的问题可能会立即关闭。
## 发行说明
每个版本的详细更改记录在[发行说明](./ChangeLog.txt)中。
## 相关
* [最新源码](https://github.com/aliyun/tea-xml)
## 许可证
[Apache-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.

View File

@ -0,0 +1,44 @@
{
"name": "alibabacloud/tea-xml",
"description": "Alibaba Cloud Tea XML Library for PHP",
"type": "library",
"license": "Apache-2.0",
"authors": [
{
"name": "Alibaba Cloud SDK",
"email": "sdk-team@alibabacloud.com"
}
],
"require": {
"php": ">5.5"
},
"require-dev": {
"phpunit/phpunit": "*",
"symfony/var-dumper": "*"
},
"autoload": {
"psr-4": {
"AlibabaCloud\\Tea\\XML\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"AlibabaCloud\\Tea\\XML\\Tests\\": "tests"
}
},
"scripts": {
"fixer": "php-cs-fixer fix ./",
"test": [
"@clearCache",
"phpunit --colors=always"
],
"clearCache": "rm -rf cache/*"
},
"config": {
"sort-packages": true,
"preferred-install": "dist",
"optimize-autoloader": true
},
"prefer-stable": true,
"minimum-stability": "dev"
}

32
vendor/alibabacloud/tea-xml/phpunit.xml vendored Normal file
View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./tests/bootstrap.php" colors="true" processIsolation="false" stopOnFailure="false"
convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true"
testSuiteLoaderFile="phpunit/src/Runner/StandardTestSuiteLoader.php">
<testsuites>
<testsuite name="All">
<directory>tests</directory>
</testsuite>
<testsuite name="Unit">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>integration</group>
</exclude>
</groups>
<logging>
<log type="coverage-html" target="cache/coverage" lowUpperBound="35" highLowerBound="70"/>
<log type="coverage-clover" target="cache/coverage.clover"/>
</logging>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,151 @@
<?php
namespace AlibabaCloud\Tea\XML;
use XmlWriter;
/**
* Based on: http://stackoverflow.com/questions/99350/passing-php-associative-arrays-to-and-from-xml.
*/
class ArrayToXml
{
private $version;
private $encoding;
/**
* Construct ArrayToXML object with selected version and encoding
* for available values check XmlWriter docs http://www.php.net/manual/en/function.xmlwriter-start-document.php.
*
* @param string $xmlVersion XML Version, default 1.0
* @param string $xmlEncoding XML Encoding, default UTF-8
*/
public function __construct($xmlVersion = '1.0', $xmlEncoding = 'utf-8')
{
$this->version = $xmlVersion;
$this->encoding = $xmlEncoding;
}
/**
* Build an XML Data Set.
*
* @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
* @param string $startElement Root Opening Tag, default data
*
* @return string XML String containing values
* @return mixed Boolean false on failure, string XML result on success
*/
public function buildXML($data, $startElement = 'data')
{
if (!\is_array($data)) {
$err = 'Invalid variable type supplied, expected array not found on line ' . __LINE__ . ' in Class: ' . __CLASS__ . ' Method: ' . __METHOD__;
trigger_error($err);
return false; //return false error occurred
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($this->version, $this->encoding);
$xml->startElement($startElement);
$data = $this->writeAttr($xml, $data);
$this->writeEl($xml, $data);
$xml->endElement(); //write end element
//returns the XML results
return $xml->outputMemory(true);
}
/**
* Write keys in $data prefixed with @ as XML attributes, if $data is an array.
* When an @ prefixed key is found, a '%' key is expected to indicate the element itself,
* and '#' prefixed key indicates CDATA content.
*
* @param XMLWriter $xml object
* @param array $data with attributes filtered out
*
* @return array $data | $nonAttributes
*/
protected function writeAttr(XMLWriter $xml, $data)
{
if (\is_array($data)) {
$nonAttributes = [];
foreach ($data as $key => $val) {
//handle an attribute with elements
if ('@' == $key[0]) {
$xml->writeAttribute(substr($key, 1), $val);
} elseif ('%' == $key[0]) {
if (\is_array($val)) {
$nonAttributes = $val;
} else {
$xml->text($val);
}
} elseif ('#' == $key[0]) {
if (\is_array($val)) {
$nonAttributes = $val;
} else {
$xml->startElement(substr($key, 1));
$xml->writeCData($val);
$xml->endElement();
}
} elseif ('!' == $key[0]) {
if (\is_array($val)) {
$nonAttributes = $val;
} else {
$xml->writeCData($val);
}
} //ignore normal elements
else {
$nonAttributes[$key] = $val;
}
}
return $nonAttributes;
}
return $data;
}
/**
* Write XML as per Associative Array.
*
* @param XMLWriter $xml object
* @param array $data Associative Data Array
*/
protected function writeEl(XMLWriter $xml, $data)
{
foreach ($data as $key => $value) {
if (\is_array($value) && !$this->isAssoc($value)) { //numeric array
foreach ($value as $itemValue) {
if (\is_array($itemValue)) {
$xml->startElement($key);
$itemValue = $this->writeAttr($xml, $itemValue);
$this->writeEl($xml, $itemValue);
$xml->endElement();
} else {
$itemValue = $this->writeAttr($xml, $itemValue);
$xml->writeElement($key, "{$itemValue}");
}
}
} elseif (\is_array($value)) { //associative array
$xml->startElement($key);
$value = $this->writeAttr($xml, $value);
$this->writeEl($xml, $value);
$xml->endElement();
} else { //scalar
$value = $this->writeAttr($xml, $value);
$xml->writeElement($key, "{$value}");
}
}
}
/**
* Check if array is associative with string based keys
* FROM: http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-sequential/4254008#4254008.
*
* @param array $array Array to check
*
* @return bool
*/
protected function isAssoc($array)
{
return (bool) \count(array_filter(array_keys($array), 'is_string'));
}
}

59
vendor/alibabacloud/tea-xml/src/XML.php vendored Normal file
View File

@ -0,0 +1,59 @@
<?php
namespace AlibabaCloud\Tea\XML;
class XML
{
public static function parseXml($xmlStr, $response)
{
$res = self::parse($xmlStr);
if ($response === null) {
return $res;
} else {
if (\is_string($response)) {
$response = new $response();
}
$prop = get_object_vars($response);
$target = [];
foreach ($res as $k => $v) {
if (isset($prop[$k])) {
$target[$k] = $v;
}
}
return $target;
}
}
public static function toXML($array)
{
$arrayToXml = new ArrayToXml();
if (\is_object($array)) {
$tmp = explode('\\', \get_class($array));
$rootName = $tmp[\count($tmp) - 1];
$data = json_decode(json_encode($array), true);
} else {
$tmp = $array;
reset($tmp);
$rootName = key($tmp);
$data = $array[$rootName];
}
ksort($data);
return $arrayToXml->buildXML($data, $rootName);
}
private static function parse($xml)
{
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(true);
}
return json_decode(
json_encode(
simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)
),
true
);
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace AlibabaCloud\Tea\XML\Tests;
use AlibabaCloud\Tea\XML\XML;
use PHPUnit\Framework\TestCase;
/**
* @internal
* @coversNothing
*/
class RpcUtilsTest extends TestCase
{
private $xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" .
"<tests>\n" .
" <name>test</name>\n" .
" <value>1</value>\n" .
"</tests>\n";
public function testParseXml()
{
$res = XML::parseXml($this->xmlStr, new tests());
$name = $res['name'];
$value = $res['value'];
$this->assertEquals('test', $name);
$this->assertEquals(1, $value);
$res = XML::parseXml($this->xmlStr, null);
$name = $res['name'];
$value = $res['value'];
$this->assertEquals('test', $name);
$this->assertEquals(1, $value);
}
public function testArrayToXML()
{
$data = [
'tests' => [
'name' => 'test',
'value' => 1,
],
];
$this->assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tests><name>test</name><value>1</value></tests>", XML::toXML($data));
}
public function testObjectToXML()
{
$obj = new tests();
$obj->name = 'test';
$obj->value = 1;
$this->assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tests><name>test</name><value>1</value></tests>", XML::toXML($obj));
}
}
class tests
{
public $name = '';
public $value = 0;
}

View File

@ -0,0 +1,3 @@
<?php
require dirname(__DIR__) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

View File

@ -31,7 +31,7 @@
"ext-simplexml": "*",
"ext-xmlwriter": "*",
"guzzlehttp/guzzle": "^6.3|^7.0",
"adbario/php-dot-notation": "^2.2"
"adbario/php-dot-notation": "^2.4"
},
"require-dev": {
"symfony/dotenv": "^3.4",

View File

@ -13,6 +13,9 @@ class TeaError extends RuntimeException
public $code = 0;
public $data;
public $name = '';
public $statusCode;
public $description;
public $accessDeniedDetail;
private $errorInfo;
/**
@ -28,10 +31,13 @@ class TeaError extends RuntimeException
parent::__construct((string) $message, (int) $code, $previous);
$this->errorInfo = $errorInfo;
if (!empty($errorInfo)) {
$properties = ['name', 'message', 'code', 'data'];
$properties = ['name', 'message', 'code', 'data', 'description', 'accessDeniedDetail'];
foreach ($properties as $property) {
if (isset($errorInfo[$property])) {
$this->{$property} = $errorInfo[$property];
if ($property === 'data' && isset($errorInfo['data']['statusCode'])) {
$this->statusCode = $errorInfo['data']['statusCode'];
}
}
}
}

View File

@ -37,6 +37,50 @@ class Helper
return \JSON_ERROR_NONE == json_last_error();
}
/**
* @param mixed $value
*
* @return bool
*/
public static function isBytes($value)
{
if (!\is_array($value)) {
return false;
}
$i = 0;
foreach ($value as $k => $ord) {
if ($k !== $i) {
return false;
}
if (!\is_int($ord)) {
return false;
}
if ($ord < 0 || $ord > 255) {
return false;
}
++$i;
}
return true;
}
/**
* Convert a bytes to string(utf8).
*
* @param array $bytes
*
* @return string the return string
*/
public static function toString($bytes)
{
$str = '';
foreach ($bytes as $ch) {
$str .= \chr($ch);
}
return $str;
}
/**
* @return array
*/

View File

@ -15,6 +15,7 @@ abstract class Parameter implements IteratorAggregate
/**
* @return ArrayIterator|Traversable
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator($this->toArray());

View File

@ -89,11 +89,15 @@ class Request extends PsrRequest
if ($this->body instanceof StreamInterface) {
$request = $request->withBody($this->body);
} else {
$body = $this->body;
if (Helper::isBytes($this->body)) {
$body = Helper::toString($this->body);
}
if (\function_exists('\GuzzleHttp\Psr7\stream_for')) {
// @deprecated stream_for will be removed in guzzlehttp/psr7:2.0
$request = $request->withBody(\GuzzleHttp\Psr7\stream_for($this->body));
$request = $request->withBody(\GuzzleHttp\Psr7\stream_for($body));
} else {
$request = $request->withBody(\GuzzleHttp\Psr7\Utils::streamFor($this->body));
$request = $request->withBody(\GuzzleHttp\Psr7\Utils::streamFor($body));
}
}
}

View File

@ -302,6 +302,7 @@ class Response extends PsrResponse implements ArrayAccess, IteratorAggregate, Co
/**
* Retrieve an external iterator.
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return $this->dot->getIterator();
@ -314,6 +315,7 @@ class Response extends PsrResponse implements ArrayAccess, IteratorAggregate, Co
*
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return $this->dot->offsetExists($offset);
@ -326,6 +328,7 @@ class Response extends PsrResponse implements ArrayAccess, IteratorAggregate, Co
*
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->dot->offsetGet($offset);
@ -337,6 +340,7 @@ class Response extends PsrResponse implements ArrayAccess, IteratorAggregate, Co
* @param $offset
* @param $value
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
$this->dot->offsetSet($offset, $value);
@ -347,6 +351,7 @@ class Response extends PsrResponse implements ArrayAccess, IteratorAggregate, Co
*
* @param $offset
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
$this->dot->offsetUnset($offset);
@ -359,6 +364,7 @@ class Response extends PsrResponse implements ArrayAccess, IteratorAggregate, Co
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count($key = null)
{
return $this->dot->count($key);

View File

@ -173,7 +173,10 @@ class Tea
public static function allowRetry(array $runtime, $retryTimes, $now)
{
unset($now);
if (empty($runtime) || !isset($runtime['maxAttempts'])) {
if (!isset($retryTimes) || null === $retryTimes || !\is_numeric($retryTimes)) {
return false;
}
if ($retryTimes > 0 && (empty($runtime) || !isset($runtime['retryable']) || !$runtime['retryable'] || !isset($runtime['maxAttempts']))) {
return false;
}
$maxAttempts = $runtime['maxAttempts'];
@ -270,6 +273,9 @@ class Tea
if (isset($config['noProxy']) && !empty($config['noProxy'])) {
$options->set('proxy.no', $config['noProxy']);
}
if (isset($config['ignoreSSL']) && !empty($config['ignoreSSL'])) {
$options->set('verify',!((bool)$config['ignoreSSL']));
}
// readTimeout&connectTimeout unit is millisecond
$read_timeout = isset($config['readTimeout']) && !empty($config['readTimeout']) ? (int) $config['readTimeout'] : 0;
$con_timeout = isset($config['connectTimeout']) && !empty($config['connectTimeout']) ? (int) $config['connectTimeout'] : 0;

View File

@ -1,97 +1,142 @@
# ChangeLog - Aliyun OSS SDK for PHP
## v2.3.1 / 2019-011-15
* translate chinese comments into english
* Added: endpoint validity check
## v2.3.0 / 2018-01-05
* Fixed: putObject support creating empty files
* Fixed: createBucket support IA/Archive
* Added: support restoreObject
* Added: support the Symlink feature
* Added: support getBucketLocation
* Added: support getBucketMeta
* Added: support proxy server Proxy
## v2.2.4 / 2017-04-25
* Fixed getObject to local file bug
## v2.2.3 / 2017-04-14
* Fixed md5 check
## v2.2.2 / 2017-01-18
* Resolve to run the connection number and memory bug on php7
## v2.2.1 / 2016-12-01
* No HTTP curl is allowed to automatically populate accept-encoding
## v2.2.0 / 2016-11-22
* Fixed PutObject/CompleteMultipartUpload return values(#26)
## v2.1.0 / 2016-11-12
* Added[RTMP](https://help.aliyun.com/document_detail/44297.html)interface
* Add support[image service](https://help.aliyun.com/document_detail/44686.html)
## v2.0.7 / 2016-06-17
* Support append object
## v2.0.6
* Trim access key id/secret and endpoint
* Refine tests and setup travis CI
## v2.0.5
* Added Add/Delete/Get BucketCname interface
## v2.0.4
* Added Put/Get Object Acl interface
## v2.0.3
* Fixing the constants in Util is defined in a PHP version that is less than 5.6.
## v2.0.2
* The problem of content-type cannot be specified when restoring multipart uploads
## v2.0.1
* Increase the ListObjects/ListMultipartUploads special characters
* Provides the interface to get the details of the OssException
## 2015.11.25
* **Large version upgrade, no longer compatible with previous interface, new version has made great improvements to ease of use, suggesting that users migrate to a new version.**
## Modify the content
* PHP 5.2 is no longer supported
### Add the cotent
* Introduce namespace
* Interface naming and modification, using hump naming
* The interface is modified, and the common parameters are extracted from the Options parameter.
* The interface returns the result modification, processing the return result, and the user can directly get the data structure easily processed 
* OssClient's constructor changes
* The Endpoint address that support CNAME and IP formats
* Rearrange the sample file organization structure and use function to organize the function points
* Add an interface that sets the connection timeout and requests timeout
* Remove the outdated interface associated with the Object Group
* The message in the OssException is changed to English
### Repair problem
* The object name is not complete
# ChangeLog - Aliyun OSS SDK for PHP
## v2.6.0 / 2022-08-03
* Added: support credentials provider.
* Fixed: compatible with swoole curl handler.
* Added: support more bucket stat info.
## v2.5.0 / 2022-05-13
* Added: support bucket transfer acceleration.
* Added: support bucket cname token.
* Added: support listobjectsV2.
## v2.4.3 / 2021-08-25
* Fixed: integer overflow in PHP5.x.
## v2.4.2 / 2021-06-04
* Compatible with PHP8.
* Fixed: compatible with PHP5.4.
* Fixed: the signature is incorrect in some scenarios
* Update: change $requestUrl from a member variable to a local variable.
## v2.4.1 / 2020-09-29
* Fixed: the getBucketPolicy bug.
## v2.4.0 / 2020-08-31
* Added: disable Expect: 100-continue
* Added: support getBucketInfo
* Added: support getBucketStat
* Added: support bucket policy
* Added: support bucket encryption
* Added: support bucket tagging
* Added: support bucket worm
* Added: support versioning
* Added: support request payment
* Added: support object tagging
* Added: support code archive
* Added: support process object
* Added: support traffic limit paramter
* Added: support upload object from file handle
* Added: support getSimplifiedObjectMeta
* Fixed: the object name can not be '0' stirng.
* Update: endpoint validity check
* Update: add new pre-signed url api
## v2.3.1 / 2019-01-15
* translate chinese comments into english
* Added: endpoint validity check
## v2.3.0 / 2018-01-05
* Fixed: putObject support creating empty files
* Fixed: createBucket support IA/Archive
* Added: support restoreObject
* Added: support the Symlink feature
* Added: support getBucketLocation
* Added: support getBucketMeta
* Added: support proxy server Proxy
## v2.2.4 / 2017-04-25
* Fixed getObject to local file bug
## v2.2.3 / 2017-04-14
* Fixed md5 check
## v2.2.2 / 2017-01-18
* Resolve to run the connection number and memory bug on php7
## v2.2.1 / 2016-12-01
* No HTTP curl is allowed to automatically populate accept-encoding
## v2.2.0 / 2016-11-22
* Fixed PutObject/CompleteMultipartUpload return values(#26)
## v2.1.0 / 2016-11-12
* Added[RTMP](https://help.aliyun.com/document_detail/44297.html)interface
* Add support[image service](https://help.aliyun.com/document_detail/44686.html)
## v2.0.7 / 2016-06-17
* Support append object
## v2.0.6
* Trim access key id/secret and endpoint
* Refine tests and setup travis CI
## v2.0.5
* Added Add/Delete/Get BucketCname interface
## v2.0.4
* Added Put/Get Object Acl interface
## v2.0.3
* Fixing the constants in Util is defined in a PHP version that is less than 5.6.
## v2.0.2
* The problem of content-type cannot be specified when restoring multipart uploads
## v2.0.1
* Increase the ListObjects/ListMultipartUploads special characters
* Provides the interface to get the details of the OssException
## 2015.11.25
* **Large version upgrade, no longer compatible with previous interface, new version has made great improvements to ease of use, suggesting that users migrate to a new version.**
## Modify the content
* PHP 5.2 is no longer supported
### Add the cotent
* Introduce namespace
* Interface naming and modification, using hump naming
* The interface is modified, and the common parameters are extracted from the Options parameter.
* The interface returns the result modification, processing the return result, and the user can directly get the data structure easily processed 
* OssClient's constructor changes
* The Endpoint address that support CNAME and IP formats
* Rearrange the sample file organization structure and use function to organize the function points
* Add an interface that sets the connection timeout and requests timeout
* Remove the outdated interface associated with the Object Group
* The message in the OssException is changed to English
### Repair problem
* The object name is not complete

View File

@ -111,7 +111,7 @@ OssClient提供的接口返回返回数据分为两种
$bucketListInfo = $ossClient->listBuckets();
$bucketList = $bucketListInfo->getBucketList();
foreach($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreateDate() . "\n");
}
```
上面代码中的$bucketListInfo的数据类型是 `OSS\Model\BucketListInfo`

View File

@ -1,150 +1,150 @@
# Alibaba Cloud OSS SDK for PHP
[![Latest Stable Version](https://poser.pugx.org/aliyuncs/oss-sdk-php/v/stable)](https://packagist.org/packages/aliyuncs/oss-sdk-php)
[![Build Status](https://travis-ci.org/aliyun/aliyun-oss-php-sdk.svg?branch=master)](https://travis-ci.org/aliyun/aliyun-oss-php-sdk)
[![Coverage Status](https://coveralls.io/repos/github/aliyun/aliyun-oss-php-sdk/badge.svg?branch=master)](https://coveralls.io/github/aliyun/aliyun-oss-php-sdk?branch=master)
## [README of Chinese](https://github.com/aliyun/aliyun-oss-php-sdk/blob/master/README-CN.md)
## Overview
Alibaba Cloud Object Storage Service (OSS) is a cloud storage service provided by Alibaba Cloud, featuring a massive capacity, security, a low cost, and high reliability. You can upload and download data on any application anytime and anywhere by calling APIs, and perform simple management of data through the web console. The OSS can store any type of files and therefore applies to various websites, development enterprises and developers.
## Run environment
- PHP 5.3+.
- cURL extension.
Tips:
- In Ubuntu, you can use the ***apt-get*** package manager to install the *PHP cURL extension*: `sudo apt-get install php5-curl`.
## Install OSS PHP SDK
- If you use the ***composer*** to manage project dependencies, run the following command in your project's root directory:
composer require aliyuncs/oss-sdk-php
You can also declare the dependency on Alibaba Cloud OSS SDK for PHP in the `composer.json` file.
"require": {
"aliyuncs/oss-sdk-php": "~2.0"
}
Then run `composer install` to install the dependency. After the Composer Dependency Manager is installed, import the dependency in your PHP code:
require_once __DIR__ . '/vendor/autoload.php';
- You can also directly download the packaged [PHAR File][releases-page], and
introduce the file to your code:
require_once '/path/to/oss-sdk-php.phar';
- Download the SDK source code, and introduce the `autoload.php` file under the SDK directory to your code:
require_once '/path/to/oss-sdk/autoload.php';
## Quick use
### Common classes
| Class | Explanation |
|:------------------|:------------------------------------|
|OSS\OSSClient | OSS client class. An OSSClient instance can be used to call the interface. |
|OSS\Core\OSSException |OSS Exception class . You only need to pay attention to this exception when you use the OSSClient. |
### Initialize an OSSClient
The SDK's operations for the OSS are performed through the OSSClient class. The code below creates an OSSClient object:
```php
<?php
$accessKeyId = "<AccessKeyID that you obtain from OSS>";
$accessKeySecret = "<AccessKeySecret that you obtain from OSS>";
$endpoint = "<Domain that you select to access an OSS data center, such as "oss-cn-hangzhou.aliyuncs.com>";
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Operations on objects
Objects are the most basic data units on the OSS. You can simply consider objects as files. The following code uploads an object:
```php
<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
$object = "<Name of the object in use. Pay attention to naming conventions>";
$content = "Hello, OSS!"; // Content of the uploaded file
try {
$ossClient->putObject($bucket, $object, $content);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Operations on buckets
Buckets are the space that you use to manage the stored objects. It is an object management unit for users. Each object must belong to a bucket. You can create a bucket with the following code:
```php
<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
try {
$ossClient->createBucket($bucket);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Handle returned results
The OSSClient provides the following two types of returned data from interfaces:
- Put and Delete interfaces: The *PUT* and *DELETE* operations are deemed successful if *null* is returned by the interfaces without *OSSException*.
- Get and List interfaces: The *GET* and *LIST* operations are deemed successful if the desired data is returned by the interfaces without *OSSException*. For example,
```php
<?php
$bucketListInfo = $ossClient->listBuckets();
$bucketList = $bucketListInfo->getBucketList();
foreach($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
}
```
In the above code, $bucketListInfo falls into the 'OSS\Model\BucketListInfo' data type.
### Run a sample project
- Modify `samples/Config.php` to complete the configuration information.
- Run `cd samples/ && php RunAll.php`.
### Run a unit test
- Run `composer install` to download the dependent libraries.
- Set the environment variable.
export OSS_ACCESS_KEY_ID=access-key-id
export OSS_ACCESS_KEY_SECRET=access-key-secret
export OSS_ENDPOINT=endpoint
export OSS_BUCKET=bucket-name
- Run `php vendor/bin/phpunit`
## License
- MIT
## Contact us
- [Alibaba Cloud OSS official website](http://oss.aliyun.com).
- [Alibaba Cloud OSS official forum](http://bbs.aliyun.com).
- [Alibaba Cloud OSS official documentation center](http://www.aliyun.com/product/oss#Docs).
- Alibaba Cloud official technical support: [Submit a ticket](https://workorder.console.aliyun.com/#/ticket/createIndex).
[releases-page]: https://github.com/aliyun/aliyun-oss-php-sdk/releases
[phar-composer]: https://github.com/clue/phar-composer
# Alibaba Cloud OSS SDK for PHP
[![Latest Stable Version](https://poser.pugx.org/aliyuncs/oss-sdk-php/v/stable)](https://packagist.org/packages/aliyuncs/oss-sdk-php)
[![Build Status](https://travis-ci.org/aliyun/aliyun-oss-php-sdk.svg?branch=master)](https://travis-ci.org/aliyun/aliyun-oss-php-sdk)
[![Coverage Status](https://coveralls.io/repos/github/aliyun/aliyun-oss-php-sdk/badge.svg?branch=master)](https://coveralls.io/github/aliyun/aliyun-oss-php-sdk?branch=master)
## [README of Chinese](https://github.com/aliyun/aliyun-oss-php-sdk/blob/master/README-CN.md)
## Overview
Alibaba Cloud Object Storage Service (OSS) is a cloud storage service provided by Alibaba Cloud, featuring a massive capacity, security, a low cost, and high reliability. You can upload and download data on any application anytime and anywhere by calling APIs, and perform simple management of data through the web console. The OSS can store any type of files and therefore applies to various websites, development enterprises and developers.
## Run environment
- PHP 5.3+.
- cURL extension.
Tips:
- In Ubuntu, you can use the ***apt-get*** package manager to install the *PHP cURL extension*: `sudo apt-get install php5-curl`.
## Install OSS PHP SDK
- If you use the ***composer*** to manage project dependencies, run the following command in your project's root directory:
composer require aliyuncs/oss-sdk-php
You can also declare the dependency on Alibaba Cloud OSS SDK for PHP in the `composer.json` file.
"require": {
"aliyuncs/oss-sdk-php": "~2.0"
}
Then run `composer install` to install the dependency. After the Composer Dependency Manager is installed, import the dependency in your PHP code:
require_once __DIR__ . '/vendor/autoload.php';
- You can also directly download the packaged [PHAR File][releases-page], and
introduce the file to your code:
require_once '/path/to/oss-sdk-php.phar';
- Download the SDK source code, and introduce the `autoload.php` file under the SDK directory to your code:
require_once '/path/to/oss-sdk/autoload.php';
## Quick use
### Common classes
| Class | Explanation |
|:------------------|:------------------------------------|
|OSS\OssClient | OSS client class. An OssClient instance can be used to call the interface. |
|OSS\Core\OssException |OSS Exception class . You only need to pay attention to this exception when you use the OssClient. |
### Initialize an OssClient
The SDK's operations for the OSS are performed through the OssClient class. The code below creates an OssClient object:
```php
<?php
$accessKeyId = "<AccessKeyID that you obtain from OSS>";
$accessKeySecret = "<AccessKeySecret that you obtain from OSS>";
$endpoint = "<Domain that you select to access an OSS data center, such as "oss-cn-hangzhou.aliyuncs.com>";
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Operations on objects
Objects are the most basic data units on the OSS. You can simply consider objects as files. The following code uploads an object:
```php
<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
$object = "<Name of the object in use. Pay attention to naming conventions>";
$content = "Hello, OSS!"; // Content of the uploaded file
try {
$ossClient->putObject($bucket, $object, $content);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Operations on buckets
Buckets are the space that you use to manage the stored objects. It is an object management unit for users. Each object must belong to a bucket. You can create a bucket with the following code:
```php
<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
try {
$ossClient->createBucket($bucket);
} catch (OssException $e) {
print $e->getMessage();
}
```
### Handle returned results
The OssClient provides the following two types of returned data from interfaces:
- Put and Delete interfaces: The *PUT* and *DELETE* operations are deemed successful if *null* is returned by the interfaces without *OSSException*.
- Get and List interfaces: The *GET* and *LIST* operations are deemed successful if the desired data is returned by the interfaces without *OSSException*. For example,
```php
<?php
$bucketListInfo = $ossClient->listBuckets();
$bucketList = $bucketListInfo->getBucketList();
foreach($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreateDate() . "\n");
}
```
In the above code, $bucketListInfo falls into the 'OSS\Model\BucketListInfo' data type.
### Run a sample project
- Modify `samples/Config.php` to complete the configuration information.
- Run `cd samples/ && php RunAll.php`.
### Run a unit test
- Run `composer install` to download the dependent libraries.
- Set the environment variable.
export OSS_ACCESS_KEY_ID=access-key-id
export OSS_ACCESS_KEY_SECRET=access-key-secret
export OSS_ENDPOINT=endpoint
export OSS_BUCKET=bucket-name
- Run `php vendor/bin/phpunit`
## License
- MIT
## Contact us
- [Alibaba Cloud OSS official website](http://oss.aliyun.com).
- [Alibaba Cloud OSS official forum](http://bbs.aliyun.com).
- [Alibaba Cloud OSS official documentation center](http://www.aliyun.com/product/oss#Docs).
- Alibaba Cloud official technical support: [Submit a ticket](https://workorder.console.aliyun.com/#/ticket/createIndex).
[releases-page]: https://github.com/aliyun/aliyun-oss-php-sdk/releases
[phar-composer]: https://github.com/clue/phar-composer

0
vendor/aliyuncs/oss-sdk-php/build-phar.sh vendored Normal file → Executable file
View File

View File

@ -14,8 +14,8 @@
"php":">=5.3"
},
"require-dev" : {
"phpunit/phpunit": "~4.0",
"satooshi/php-coveralls": "~1.0"
"phpunit/phpunit": "*",
"satooshi/php-coveralls": "*"
},
"minimum-stability": "stable",
"autoload": {

View File

@ -18,6 +18,24 @@ Common::println("bucket $bucket created");
$doesExist = $ossClient->doesBucketExist($bucket);
Common::println("bucket $bucket exist? " . ($doesExist ? "yes" : "no"));
// Get the region of bucket
$regions = $ossClient->getBucketLocation($bucket);
Common::println("bucket $bucket region: " .print_r($regions,true));
// Get the meta of a bucket
$metas = $ossClient->getBucketMeta($bucket);
Common::println("bucket $bucket meta: " .print_r($metas,true));
// Get the info of bucket
$info = $ossClient->getBucketInfo($bucket);
Common::println("bucket name:".$info->getName()."\n");
Common::println("bucket location:". $info->getLocation()."\n");
Common::println("bucket creation time:".$info->getCreateDate()."\n");
Common::println("bucket storage class:".$info->getStorageClass()."\n");
Common::println("bucket extranet endpoint:".$info->getExtranetEndpoint()."\n");
Common::println("bucket intranet endpoint:".$info->getIntranetEndpoint()."\n");
// Get the bucket list
$bucketListInfo = $ossClient->listBuckets();
@ -33,6 +51,9 @@ Common::println("bucket $bucket acl get: " . $acl);
createBucket($ossClient, $bucket);
doesBucketExist($ossClient, $bucket);
getBucketLocation($ossClient, $bucket);
getBucketMeta($ossClient,$bucket);
getBucketInfo($ossClient, $bucket);
deleteBucket($ossClient, $bucket);
putBucketAcl($ossClient, $bucket);
getBucketAcl($ossClient, $bucket);
@ -82,6 +103,71 @@ function doesBucketExist($ossClient, $bucket)
}
}
/**
* Get the info of bucket
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
*/
function getBucketInfo($ossClient, $bucket)
{
try {
$info = $ossClient->getBucketInfo($bucket);
printf("bucket name:%s\n", $info->getName());
printf("bucket location:%s\n", $info->getLocation());
printf("bucket creation time:%s\n", $info->getCreateDate());
printf("bucket storage class:%s\n", $info->getStorageClass());
printf("bucket extranet endpoint:%s\n", $info->getExtranetEndpoint());
printf("bucket intranet endpoint:%s\n", $info->getIntranetEndpoint());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get the meta of a bucket
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
*/
function getBucketLocation($ossClient, $bucket)
{
try {
$regions = $ossClient->getBucketLocation($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print("bucket $bucket region: " .print_r($regions,true));
}
/**
* Get the bucket's meta
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
*/
function getBucketMeta($ossClient, $bucket)
{
try {
$metas = $ossClient->getBucketMeta($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print("bucket $bucket meta: " .print_r($metas,true));
}
/**
* Delete a bucket. If the bucket is not empty, the deletion fails.
* A bucket which is not empty indicates that it does not contain any objects or parts that are not completely uploaded during multipart upload

View File

@ -0,0 +1,91 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************Simple Usage ***************************************************************
// Add Canme record
$myDomain = '<yourDomainName>';
$ossClient->addBucketCname($bucket, $myDomain);
// View cname records
$cnameConfig = $ossClient->getBucketCname($bucket);
Common::println("bucket $bucket cname:" . $cnameConfig->serializeToXml());
// Delete bucket cname
$myDomain = '<yourDomainName>';
$ossClient->deleteBucketCname($bucket,$myDomain);
Common::println("bucket $bucket cname deleted");
//******************************* For complete usage, see the following functions ****************************************************
addBucketCname($ossClient, $bucket);
getBucketCname($ossClient, $bucket);
deleteBucketCname($ossClient, $bucket);
/**
* Set bucket cname
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function addBucketCname($ossClient, $bucket)
{
// Set up a custom domain name.
$myDomain = '<yourDomainName>';
try {
$ossClient->addBucketCname($bucket, $myDomain);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get bucket cname
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketCname($ossClient, $bucket)
{
try {
$cnameConfig = $ossClient->getBucketCname($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($cnameConfig->serializeToXml() . "\n");
}
/**
* Delete bucket cname
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteBucketCname($ossClient, $bucket)
{
$myDomain = '<yourDomainName>';
try {
$ossClient->deleteBucketCname($bucket, $myDomain);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,98 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\ServerSideEncryptionConfig;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Configure Bucket encryption
// Set Bucket's default server-side encryption method to OSS fully managed encryption (SSE-OSS).
$config = new ServerSideEncryptionConfig("AES256");
// Set Bucket's default server-side encryption method to KMS, and do not specify a CMK ID.
//$config = new ServerSideEncryptionConfig("KMS");
// Set Bucket's default server-side encryption method to KMS, and specify the CMK ID.
//$config = new ServerSideEncryptionConfig("KMS", "your kms id");
$ossClient->putBucketEncryption($bucket, $config);
Common::println("bucket $bucket encryoption created");
$config = $ossClient->getBucketEncryption($bucket);
Common::println("bucket $bucket encryoption:".$config->serializeToXml());
$config = $ossClient->deleteBucketEncryption($bucket);
Common::println("bucket $bucket encryoption has deleted");
//******************************* For complete usage, see the following functions ****************************************************
putBucketEncryption($ossClient, $bucket);
getBucketEncryption($ossClient, $bucket);
deleteBucketEncryption($ossClient, $bucket);
/**
* Configure Bucket encryption
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketEncryption($ossClient,$bucket){
try {
// Set Bucket's default server-side encryption method to OSS fully managed encryption (SSE-OSS).
$config = new ServerSideEncryptionConfig("AES256");
// Set Bucket's default server-side encryption method to KMS, and do not specify a CMK ID.
//$config = new ServerSideEncryptionConfig("KMS");
// Set Bucket's default server-side encryption method to KMS, and specify the CMK ID.
//$config = new ServerSideEncryptionConfig("KMS", "your kms id");
$ossClient->putBucketEncryption($bucket, $config);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get Bucket encryption
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketEncryption($ossClient,$bucket){
try {
$config = $ossClient->getBucketEncryption($bucket);
print($config->getSSEAlgorithm());
print($config->getKMSMasterKeyID());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Delete Bucket encryption
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function deleteBucketEncryption($ossClient,$bucket){
try {
$ossClient->deleteBucketEncryption($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,116 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
//Set requester payment mode
$ossClient->putBucketRequestPayment($bucket, "Requester");
//Get requester payment mode configuration
$payer = $ossClient->getBucketRequestPayment($bucket);
Common::println("bucket $bucket Payer:".$payer.PHP_EOL);
//Third-party paid access to Object
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_REQUEST_PAYER => 'requester',
));
$content = "hello";
$object = "object";
//PutObject interface to specify the payer
$ossClient->putObject($bucket, $object, $content, $options);
// GetObject interface to specify the payer
$ossClient->getObject($bucket, $object, $options);
// DeleteObject interface to specify the payer
$ossClient->deleteObject($bucket, $object, $options);
//******************************* For complete usage, see the following functions ****************************************************
putBucketRequestPayment($ossClient,$bucket);
getBucketRequestPayment($ossClient,$bucket);
setObjectPayment($ossClient,$bucket);
/**
* Set requester payment mode
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketRequestPayment($ossClient, $bucket)
{
try {
$ossClient->putBucketRequestPayment($bucket, "Requester");
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get payment mode of bucket
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketRequestPayment($ossClient, $bucket)
{
try {
$payer = $ossClient->getBucketRequestPayment($bucket);
print("bucket $bucket Payer:".$payer.PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Set payment mode of object
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function setObjectPayment($ossClient,$bucket){
// Specify the payment model for the requester.
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_REQUEST_PAYER => 'requester',
));
try {
$content = "hello";
$object = "object";
//PutObject interface to specify the payer
$ossClient->putObject($bucket, $object, $content, $options);
// GetObject interface to specify the payer
$ossClient->getObject($bucket, $object, $options);
// DeleteObject interface to specify the payer
$ossClient->deleteObject($bucket, $object, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,123 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Set Bucket Policy
// Authorization strategy.
$policy = <<< BBBB
{
"Version":"1",
"Statement":[
{
"Action":[
"oss:PutObject",
"oss:GetObject"
],
"Effect":"Allow",
"Resource":["acs:oss:*:*:*/user1/*"]
}
]
}
BBBB;
$ossClient->putBucketPolicy($bucket, $policy);
// Get bucket pllicy
$policy = $ossClient->getBucketPolicy($bucket);
Common::println("bucket $bucket policy: " . $policy);
// Delete bucket pllicy
$policy = $ossClient->deleteBucketPolicy($bucket);
//******************************* For complete usage, see the following functions ****************************************************
putBucketPolicy($ossClient, $bucket);
getBucketPolicy($ossClient, $bucket);
deleteBucketPolicy($ossClient, $bucket);
/**
* Set Bucket Policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketPolicy($ossClient, $bucket)
{
$policy = <<< BBBB
{
"Version":"1",
"Statement":[
{
"Action":[
"oss:PutObject",
"oss:GetObject"
],
"Effect":"Allow",
"Resource":["acs:oss:*:*:*/user1/*"]
}
]
}
BBBB;
try {
$ossClient->putBucketPolicy($bucket, $policy);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get Bucket Policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketPolicy($ossClient, $bucket)
{
try {
$policy = $ossClient->getBucketPolicy($bucket);
print($policy);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Delete Bucket Policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function deleteBucketPolicy($ossClient, $bucket)
{
try {
$ossClient->deleteBucketPolicy($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,65 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Get Bucket Stat
$stat = $ossClient->getBucketStat($bucket);
Common::println("Bucket ".$bucket." current storage is:".$stat->getStorage().PHP_EOL);
Common::println("Bucket ".$bucket." object count is:".$stat->getObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." multipart upload count is:".$stat->getMultipartUploadCount().PHP_EOL);
Common::println("Bucket ".$bucket." live channel count is:".$stat->getLiveChannelCount().PHP_EOL);
Common::println("Bucket ".$bucket." last modified time is:".$stat->getLastModifiedTime().PHP_EOL);
Common::println("Bucket ".$bucket." standard storage is:".$stat->getStandardStorage().PHP_EOL);
Common::println("Bucket ".$bucket." standard object count is:".$stat->getStandardObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." infrequent access storage is:".$stat->getInfrequentAccessStorage().PHP_EOL);
Common::println("Bucket ".$bucket." infrequent access real storage is:".$stat->getInfrequentAccessRealStorage().PHP_EOL);
Common::println("Bucket ".$bucket." infrequent access object count is:".$stat->getInfrequentAccessObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." archive storage is:".$stat->getArchiveStorage().PHP_EOL);
Common::println("Bucket ".$bucket." archive real storage is:".$stat->getArchiveRealStorage().PHP_EOL);
Common::println("Bucket ".$bucket." archive object count is:".$stat->getArchiveObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." cold archive storage is:".$stat->getColdArchiveStorage().PHP_EOL);
Common::println("Bucket ".$bucket." cold archive real storage is:".$stat->getColdArchiveRealStorage().PHP_EOL);
Common::println("Bucket ".$bucket." cold archive object count is:".$stat->getColdArchiveObjectCount().PHP_EOL);
//******************************* For complete usage, see the following functions ****************************************************
getBucketStat($ossClient,$bucket);
/**
* get bucket stat
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketStat($ossClient, $bucket)
{
try {
$stat = $ossClient->getBucketStat($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf("Bucket ".$bucket." current storage is:".$stat->getStorage().PHP_EOL);
printf("Bucket ".$bucket." object count is:".$stat->getObjectCount().PHP_EOL);
printf("Bucket ".$bucket." multipart upload count is:".$stat->getMultipartUploadCount().PHP_EOL);
printf("Bucket ".$bucket." live channel count is:".$stat->getLiveChannelCount().PHP_EOL);
printf("Bucket ".$bucket." last modified time is:".$stat->getLastModifiedTime().PHP_EOL);
printf("Bucket ".$bucket." standard storage is:".$stat->getStandardStorage().PHP_EOL);
printf("Bucket ".$bucket." standard object count is:".$stat->getStandardObjectCount().PHP_EOL);
printf("Bucket ".$bucket." infrequent access storage is:".$stat->getInfrequentAccessStorage().PHP_EOL);
printf("Bucket ".$bucket." infrequent access real storage is:".$stat->getInfrequentAccessRealStorage().PHP_EOL);
printf("Bucket ".$bucket." infrequent access object count is:".$stat->getInfrequentAccessObjectCount().PHP_EOL);
printf("Bucket ".$bucket." archive storage is:".$stat->getArchiveStorage().PHP_EOL);
printf("Bucket ".$bucket." archive real storage is:".$stat->getArchiveRealStorage().PHP_EOL);
printf("Bucket ".$bucket." archive object count is:".$stat->getArchiveObjectCount().PHP_EOL);
printf("Bucket ".$bucket." cold archive storage is:".$stat->getColdArchiveStorage().PHP_EOL);
printf("Bucket ".$bucket." cold archive real storage is:".$stat->getColdArchiveRealStorage().PHP_EOL);
printf("Bucket ".$bucket." cold archive object count is:".$stat->getColdArchiveObjectCount().PHP_EOL);
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,112 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\TaggingConfig;
use OSS\Model\Tag;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Set bucket tag
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
$ossClient->putBucketTags($bucket, $config);
// Get bucket tags
$config = $ossClient->getBucketTags($bucket);
Common::println("bucket $bucket tags: ".$config->serializeToXml());
// Delete bucket tags
// Delete the specified tag of the bucket.
$tags = array();
$tags[] = new Tag("key1", "value1");
$tags[] = new Tag("key2", "value2");
$ossClient->deleteBucketTags($bucket, $tags);
// Delete all tags in the bucket.
$ossClient->deleteBucketTags($bucket);
//******************************* For complete usage, see the following functions ****************************************************
putBucketTags($ossClient, $bucket);
getBucketTags($ossClient, $bucket);
deleteBucketTags($ossClient, $bucket);
/**
* Create bucket tag
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketTags($ossClient, $bucket)
{
try {
// 设置Bucket标签。
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
$ossClient->putBucketTags($bucket, $config);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* get bucket tag
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketTags($ossClient, $bucket)
{
try {
$config = $ossClient->getBucketTags($bucket);
print_r($config->getTags());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* delete bucket tag
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function deleteBucketTags($ossClient, $bucket)
{
try {
// Delete the specified tag of the bucket.
$tags = array();
$tags[] = new Tag("key1", "value1");
$tags[] = new Tag("key2", "value2");
$ossClient->deleteBucketTags($bucket, $tags);
// Delete all tags in the bucket.
//$ossClient->deleteBucketTags($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,61 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// set <tran></tran>sfer acceleration
$enabled = true; // set true to enable transfer acceleration; set false to disalbe transfer acceleration
$ossClient->putBucketTransferAcceleration($bucket, $enabled);
printf('putBucketTransferAcceleration SUCCESS' . "\n");
// get transfer acceleration
$result = $ossClient->getBucketTransferAcceleration($bucket);
printf('getBucketTransferAcceleration Status:%s'."\n",$result);
//******************************* For complete usage, see the following functions ****************************************************
putBucketTransferAcceleration($ossClient,$bucket);
getBucketTransferAcceleration($bucket);
/**
* @param $ossClient OssClient
* @param $bucket bucket_name string
* @param $enabled string
*/
function putBucketTransferAcceleration($ossClient, $bucket, $enabled)
{
try{
$enabled = true; // set true to enable transfer acceleration; set false to disalbe transfer acceleration
$ossClient->putBucketTransferAcceleration($bucket,$enabled);
printf('putBucketTransferAcceleration SUCCESS' . "\n");
} catch(OssException $e) {
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function getBucketTransferAcceleration($ossClient, $bucket)
{
try{
$result = $ossClient->getBucketTransferAcceleration($bucket);
printf('getBucketTransferAcceleration Status:%s'."\n",$result);
} catch(OssException $e) {
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,235 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
//Set Bucket version control status
//Set the storage space version control to enable version control (Enabled) or suspend version control (Suspended).
$ossClient->putBucketVersioning($bucket, "Enabled");
Common::println("bucket $bucket version Enabled");
// show all object list
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option = array(
OssClient::OSS_KEY_MARKER => $result->getNextKeyMarker(),
OssClient::OSS_VERSION_ID_MARKER => $result->getNextVersionIdMarker()
);
} else {
$bool = false;
}
}
// show the prefix object
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_PREFIX => "test"
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
// list the number of objects
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_MAX_KEYS => 200
);
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
// show root folder list
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_DELIMITER => "/",
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
// Show subfolder objects list
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_DELIMITER => "/",
OssClient::OSS_PREFIX => "test/",
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
//******************************* For complete usage, see the following functions ****************************************************
listObjectVersions($ossClient, $bucket);
putBucketVersioning($ossClient, $bucket);
/**
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function listObjectVersions($ossClient, $bucket)
{
try {
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Enabled or Suspended bucket version
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketVersioning($ossClient, $bucket)
{
try {
//Set the storage space version control to enable version control (Enabled) or suspend version control (Suspended).
$ossClient->putBucketVersioning($bucket, "Enabled");
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,145 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Create a new compliance retention policy:
// The specified object protection days are 30 days.
$wormId = $ossClient->initiateBucketWorm($bucket, 30);
Common::println("bucket $bucket wormId: " . $wormId.PHP_EOL);
// Cancel an unlocked compliance retention policy
$ossClient->abortBucketWorm($bucket);
//Lock compliant retention policy
$wormId = $ossClient->initiateBucketWorm($bucket, 30);
$ossClient->completeBucketWorm($bucket, $wormId);
// Get compliant retention policy
$config = $ossClient->getBucketWorm($bucket);
Common::println("WormId:".$config->getWormId().PHP_EOL);
Common::println("State:". $config->getState().PHP_EOL);
Common::println("Day:". $config->getDay().PHP_EOL);
// Extend the retention days of objects
$wormId = "<yourWormId>";
// Extend the retention days of objects in the locked compliance retention policy to 120 days.
$ossClient->extendBucketWorm($bucket, $wormId, 120);
//******************************* For complete usage, see the following functions ****************************************************
initiateBucketWorm($ossClient, $bucket);
abortBucketWorm($ossClient, $bucket);
completeBucketWorm($ossClient, $bucket);
getBucketWorm($ossClient, $bucket);
extendBucketWorm($ossClient, $bucket);
/**
* Set Bucket Worm Ploicy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function initiateBucketWorm($ossClient, $bucket)
{
try {
$wormId = $ossClient->initiateBucketWorm($bucket,30);
print("bucket $bucket wormId: " . $wormId.PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Cancel an unlocked compliance retention policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function abortBucketWorm($ossClient, $bucket)
{
try {
$ossClient->abortBucketWorm($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Complete Bucket Worm
* @param $ossClient $ossClient OssClient instance
* @param $bucket $bucket Name of the bucket to create
*/
function completeBucketWorm($ossClient, $bucket)
{
try {
$wormId = $ossClient->initiateBucketWorm($bucket, 30);
$ossClient->completeBucketWorm($bucket, $wormId);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get Bucket Worm
* @param $ossClient $ossClient OssClient instance
* @param $bucket $bucket Name of the bucket to create
*/
function getBucketWorm($ossClient, $bucket)
{
try {
$config = $ossClient->getBucketWorm($bucket);
printf("WormId:%s\n", $config->getWormId());
printf("State:%s\n", $config->getState());
printf("Day:%d\n", $config->getDay());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Extend the retention days of objects
* @param $ossClient $ossClient OssClient instance
* @param $bucket $bucket Name of the bucket to create
*/
function extendBucketWorm($ossClient, $bucket)
{
$wormId = "<yourWormId>";
try {
$ossClient->ExtendBucketWorm($bucket, $wormId, 120);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,76 @@
<?php
//=============================================================================
//How to use credentials-php to access oss
// step 1:Install credentials-php composer require alibabacloud/credentials
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Credentials\CredentialsProvider;
use AlibabaCloud\Credentials\Credential;
use OSS\Credentials\StaticCredentialsProvider;
// public provider conversion class
class AlibabaCloudCredentialsWrapper implements CredentialsProvider{
/**
* @var Credential
*/
private $warpper;
public function __construct($credential){
$this->warpper = $credential;
}
public function getCredentials(){
$ak = $this->warpper->getAccessKeyId();
$sk = $this->warpper->getAccessKeySecret();
$token = $this->warpper->getSecurityToken();
return new StaticCredentialsProvider($ak, $sk, $token);
}
}
$bucket = Common::getBucketName();
//AccessKey Credentials demo
$credential = new Credential(array(
'type' => 'access_key',
'access_key_id' => '<access_key_id>',
'access_key_secret' => '<accessKey_secret>',
));
$providerWarpper = new AlibabaCloudCredentialsWrapper($credential);
$config = array(
'provider' => $providerWarpper,
'endpoint'=> '<endpoint>'
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of access key');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
// EcsRamRole Credentials demo
$ecsRamRole = new Credential(array(
'type' => 'ecs_ram_role',
'role_name' => 'EcsRamRoleOssTest',
));
$providerWarpper = new AlibabaCloudCredentialsWrapper($ecsRamRole);
$bucket = 'oss-bucket-cd-yp-test';
$config = array(
'provider' => $providerWarpper,
'endpoint'=> '<endpoint>'
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of EcsRamRole');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}

View File

@ -0,0 +1,45 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Credentials\StaticCredentialsProvider;
$bucket = Common::getBucketName();
// Access Key Provider demo
$id = '<access_key_id>';
$secret = '<accessKey_secret>';
$provider = new StaticCredentialsProvider($id,$secret);
$config = array(
'provider' => $provider,
'endpoint'=>'<endpoint>'
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of access key provider');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
// Sts provider demo
$id = '<access_key_id>';
$secret = '<accessKey_secret>';
$token = '<security_token>';
$provider = new StaticCredentialsProvider($id,$secret,$token);
$config = array(
'provider' => $provider,
'endpoint'=> "<endpoint>"
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of sts provider');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}

View File

@ -83,5 +83,5 @@ function printImage($func, $imageFile)
Common::println("$func, image width: " . $array[0]);
Common::println("$func, image height: " . $array[1]);
Common::println("$func, image type: " . ($array[2] === 2 ? 'jpg' : 'png'));
Common::println("$func, image size: " . ceil(filesize($imageFile)));
Common::println("$func, image size: " . ceil(sprintf('%u',filesize($imageFile))));
}

View File

@ -85,7 +85,7 @@ function putObjectByRawApis($ossClient, $bucket)
*/
$partSize = 10 * 1024 * 1024;
$uploadFile = __FILE__;
$uploadFileSize = filesize($uploadFile);
$uploadFileSize = sprintf('%u',filesize($uploadFile));
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;

View File

@ -3,6 +3,7 @@ require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\RestoreConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
@ -48,6 +49,17 @@ $ossClient->getObject($bucket, "c.file", $options);
Common::println("b.file is fetched to the local file: c.file.localcopy");
Common::println("b.file is created");
// Restore Object
$day = 3;
$tier = 'Expedited';
$config = new RestoreConfig($day,$tier);
$options = array(
OssClient::OSS_RESTORE_CONFIG => $config
);
$ossClient->restoreObject($bucket, 'b.file',$options);
// Copy an object
$result = $ossClient->copyObject($bucket, "c.file", $bucket, "c.file.copy");
Common::println("lastModifiedTime: " . $result[0]);
@ -75,9 +87,37 @@ foreach($result as $object)
sleep(2);
unlink("c.file.localcopy");
// Normal upload and download speed limit
$object= "b.file";
$content = "hello world";
// The speed limit is 100 KB/s, which is 819200 bit/s.
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
));
// Speed limit upload.
$ossClient->putObject($bucket, $object, $content, $options);
// Speed limit download.
$ossClient->getObject($bucket, $object, $options);
// Signed URL upload and download speed limit
// Create a URL for uploading with a limited rate, and the validity period is 60s.
$timeout = 60;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
Common::println("b.file speed limit upload url:".$signedUrl.PHP_EOL);
// Create a URL for speed-limited downloads, with a validity period of 120s.
$timeout = 120;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
Common::println("b.file speed limit download url:".$signedUrl.PHP_EOL);
//******************************* For complete usage, see the following functions ****************************************************
listObjects($ossClient, $bucket);
listObjectsV2($ossClient, $bucket);
listAllObjects($ossClient, $bucket);
createObjectDir($ossClient, $bucket);
putObject($ossClient, $bucket);
@ -92,6 +132,11 @@ deleteObjects($ossClient, $bucket);
doesObjectExist($ossClient, $bucket);
getSymlink($ossClient, $bucket);
putSymlink($ossClient, $bucket);
putObjectSpeed($ossClient, $bucket);
getObjectSpeed($ossClient, $bucket);
signUrlSpeedUpload($ossClient, $bucket);
signUrlSpeedDownload($ossClient, $bucket);
restoreObject($ossClient,$bucket);
/**
* Create a 'virtual' folder
*
@ -194,6 +239,10 @@ function listObjects($ossClient, $bucket)
print("objectList:\n");
foreach ($objectList as $objectInfo) {
print($objectInfo->getKey() . "\n");
if($objectInfo->getOwner() != null){
printf("owner id:".$objectInfo->getOwner()->getId() . "\n");
printf("owner name:".$objectInfo->getOwner()->getDisplayName() . "\n");
}
}
}
if (!empty($prefixList)) {
@ -204,6 +253,55 @@ function listObjects($ossClient, $bucket)
}
}
/**
* Lists all files and folders in the bucket.
* Note if there's more items than the max-keys specified, the caller needs to use the nextMarker returned as the value for the next call's maker paramter.
* Loop through all the items returned from ListObjects.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function listObjectsV2($ossClient, $bucket)
{
$prefix = 'oss-php-sdk-test/';
$delimiter = '/';
$maxkeys = 1000;
$options = array(
'delimiter' => $delimiter,
'prefix' => $prefix,
'max-keys' => $maxkeys,
'start-after' =>'test-object',
'fetch-owner' =>'true',
);
try {
$listObjectInfo = $ossClient->listObjectsV2($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
$objectList = $listObjectInfo->getObjectList(); // object list
$prefixList = $listObjectInfo->getPrefixList(); // directory list
if (!empty($objectList)) {
print("objectList:\n");
foreach ($objectList as $objectInfo) {
print($objectInfo->getKey() . "\n");
if($objectInfo->getOwner() != null){
printf("owner id:".$objectInfo->getOwner()->getId() . "\n");
printf("owner name:".$objectInfo->getOwner()->getDisplayName() . "\n");
}
}
}
if (!empty($prefixList)) {
print("prefixList: \n");
foreach ($prefixList as $prefixInfo) {
print($prefixInfo->getPrefix() . "\n");
}
}
}
/**
* Lists all folders and files under the bucket. Use nextMarker repeatedly to get all objects.
*
@ -516,3 +614,116 @@ function doesObjectExist($ossClient, $bucket)
var_dump($exist);
}
/**
* Speed limit upload.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putObjectSpeed($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$content = file_get_contents(__FILE__);
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
));
try {
$ossClient->putObject($bucket, $object, $content, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Speed limit download.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getObjectSpeed($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
));
try {
$ossClient->getObject($bucket, $object, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Speed limit download.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function signUrlSpeedUpload($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$timeout = 120;
$options = array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
);
$timeout = 60;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
print($signedUrl);
}
/**
* Speed limit download.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function signUrlSpeedDownload($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$timeout = 120;
$options = array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
);
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print($signedUrl);
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Restore object
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function restoreObject($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
$day = 3;
$tier = 'Expedited';
$config = new RestoreConfig($day,$tier);
$options = array(
OssClient::OSS_RESTORE_CONFIG => $config
);
try {
$ossClient->restoreObject($bucket, $object,$options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -0,0 +1,366 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Core\OssUtil;
use OSS\Model\TaggingConfig;
use OSS\Model\Tag;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple usage ***************************************************************
// Upload Object add tag
$object = "b.file";
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
)
);
$result = $ossClient->putObject($bucket, $object, __FILE__,$options);
Common::println("b.file is created");
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging']);
// Add object tags when uploading parts
$object = "b.file";
$file = __FILE__;
$options = array(
OssClient::OSS_CHECK_MD5 => true,
OssClient::OSS_PART_SIZE => 1,
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
),
);
$result = $ossClient->multiuploadFile($bucket, $object, $file, $options);
Common::println("b.file is created");
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging']);
// get tags from object
$object = "a.txt";
$result = $ossClient->getObjectTagging($bucket,$object);
printf($object.'tags is: '.$result->serializeToXml().PHP_EOL);
// Add or change object tags to uploaded objects
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
$ossClient->putObjectTagging($bucket, $object, $config);
// Add object tags when uploading
$object = "a.txt";
$filePath = "D:\\localpath\\b.txt";
$filePath1 = "D:\\localpath\\c.txt";
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2',
)
);
$position = $ossClient->appendObject($bucket, $object,'content one',0,$options);
printf('Content one append object Success'.PHP_EOL);
$position = $ossClient->appendObject($bucket, $object, 'content two',$position,$options);
printf('Content two append object Success'.PHP_EOL);
// delete tags
$object = "g.file";
$ossClient->deleteObjectTagging($bucket, $object);
printf($object.' tags has deleted'.PHP_EOL);
// Copy a small file
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging-directive' => 'Replace',
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
$ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $options);
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println('object tags is:'.$config->serializeToXml());
// Copy a large file
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
$part_size = 256*1024*1024;
$objectMeta = $ossClient->getObjectMeta($fromBucket, $fromObject);
$length = $objectMeta['content-length'];
$upload_id = $ossClient->initiateMultipartUpload($toBucket, $toObject,$options);
$pieces = $ossClient->generateMultiuploadParts($length, $part_size);
$response_upload_part = array();
$copyId = 1;
$upload_position = 0;
foreach ($pieces as $i => $piece) {
$from_pos = $upload_position + (integer)$piece['seekTo'];
$to_pos = (integer)$piece['length'] + $from_pos - 1;
$up_options = array(
'start' => $from_pos,
'end' => $to_pos,
);
$response_upload_part[] = $ossClient->uploadPartCopy( $fromBucket, $fromObject, $toBucket, $toObject, $copyId, $upload_id, $up_options);
printf("initiateMultipartUpload, uploadPartCopy - part#{$copyId} OK\n");
$copyId = $copyId + 1;
}
$upload_parts = array();
foreach ($response_upload_part as $i => $etag) {
$upload_parts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $etag,
);
}
$result = $ossClient->completeMultipartUpload($toBucket, $toObject, $upload_id, $upload_parts);
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println($toObject.' tags is:'.$config->serializeToXml());
//******************************* For complete usage, see the following functions ****************************************************
putObject($ossClient,$bucket);
multiuploadFile($ossClient,$bucket);
appendObject($ossClient,$bucket);
putObjectTagging($ossClient,$bucket);
getObjectTagging($ossClient,$bucket);
deleteObjectTagging($ossClient,$bucket);
copyObjectSmall($ossClient,$bucket);
copyObjectLarge($ossClient,$bucket);
/**
* Upload Object add tag
* @param $ossClient OssClient
* @param $bucket bucket_name
*/
function putObject($ossClient,$bucket){
$object = "b.file";
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
));
try {
// 通过简单上传的方式上传Object。
$result = $ossClient->putObject($bucket, $object, __FILE__,$options);
Common::println("b.file is created".PHP_EOL);
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging'].PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Add object tags when uploading parts
* @param $ossClient OssClient
* @param $bucket bucket_name
*/
function multiuploadFile($ossClient,$bucket){
$object = "b.file";
$file = __FILE__;
$options = array(
OssClient::OSS_CHECK_MD5 => true,
OssClient::OSS_PART_SIZE => 1,
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
),
);
try {
$result = $ossClient->multiuploadFile($bucket, $object, $file, $options);
Common::println("b.file is created".PHP_EOL);
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging'].PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Add object tags when uploading
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function appendObject($ossClient,$bucket){
$object = "g.file";
$content_array = array('Hello OSS', 'Hi OSS');
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2',
));
try {
$position = $ossClient->appendObject($bucket, $object, $content_array[0], 0, $options);
printf($content_array[0].' append object Success'.PHP_EOL);
$position = $ossClient->appendObject($bucket, $object, $content_array[1], $position);
printf($content_array[1].' append object Success'.PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* @param $ossClient OssClient
* @param $bucket bucket_name string
* @throws OssException
*/
function putObjectTagging($ossClient,$bucket){
$object = "g.file";
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
try {
$ossClient->putObjectTagging($bucket, $object, $config);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* get object tags
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function getObjectTagging($ossClient,$bucket){
$object = "g.file";
try {
$config = $ossClient->getObjectTagging($bucket, $object);
printf($object." tags is:".$config->serializeToXml().PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* get object tags
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function deleteObjectTagging($ossClient,$bucket){
$object = "g.file";
try {
$ossClient->deleteObjectTagging($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Copy small files
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function copyObjectSmall($ossClient,$bucket){
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging-directive' => 'Replace',
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
try {
$ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println('object tags is:'.$config->serializeToXml());
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Copy a large file
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function copyObjectLarge($ossClient,$bucket){
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
$part_size = 256*1024*1024;
try{
$objectMeta = $ossClient->getObjectMeta($fromBucket, $fromObject);
$length = $objectMeta['content-length'];
$upload_id = $ossClient->initiateMultipartUpload($toBucket, $toObject,$options);
$pieces = $ossClient->generateMultiuploadParts($length, $part_size);
$response_upload_part = array();
$copyId = 1;
$upload_position = 0;
foreach ($pieces as $i => $piece) {
$from_pos = $upload_position + (integer)$piece['seekTo'];
$to_pos = (integer)$piece['length'] + $from_pos - 1;
$up_options = array(
'start' => $from_pos,
'end' => $to_pos,
);
$response_upload_part[] = $ossClient->uploadPartCopy( $fromBucket, $fromObject, $toBucket, $toObject, $copyId, $upload_id, $up_options);
printf("initiateMultipartUpload, uploadPartCopy - part#{$copyId} OK\n");
$copyId = $copyId + 1;
}
$upload_parts = array();
foreach ($response_upload_part as $i => $etag) {
$upload_parts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $etag,
);
}
$result = $ossClient->completeMultipartUpload($toBucket, $toObject, $upload_id, $upload_parts);
printf('copy success'. "\n");
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println($toObject.' tags is:'.$config->serializeToXml());
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@ -130,7 +130,7 @@ function getSignedUrlForPuttingObjectFromFile($ossClient, $bucket)
$request->set_method('PUT');
$request->add_header('Content-Type', 'txt');
$request->set_read_file($file);
$request->set_read_stream_size(filesize($file));
$request->set_read_stream_size(sprintf('%u',filesize($file)));
$request->send_request();
$res = new ResponseCore($request->get_response_header(),
$request->get_response_body(), $request->get_response_code());

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,63 @@
<?php
namespace OSS\Credentials;
use OSS\Core\OssException;
/**
* Basic implementation of the OSS Credentials that allows callers to
* pass in the OSS Access Key and OSS Secret Access Key in the constructor.
*/
class Credentials
{
private $key;
private $secret;
private $token;
/**
* Constructor a new BasicOSSCredentials object, with the specified OSS
* access key and OSS secret key
*
* @param string $key OSS access key ID
* @param string $secret OSS secret access key
* @param string $token Security token to use
*/
public function __construct($key, $secret, $token = null)
{
if (empty($key)) {
throw new OssException("access key id is empty");
}
if (empty($secret)) {
throw new OssException("access key secret is empty");
}
$this->key = trim($key);
$this->secret = trim($secret);
$this->token = $token;
}
/**
* @return string
*/
public function getAccessKeyId()
{
return $this->key;
}
/**
* @return string
*/
public function getAccessKeySecret()
{
return $this->secret;
}
/**
* @return string|null
*/
public function getSecurityToken()
{
return $this->token;
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace OSS\Credentials;
interface CredentialsProvider
{
/**
* @return Credentials
*/
public function getCredentials();
}

View File

@ -0,0 +1,35 @@
<?php
namespace OSS\Credentials;
/**
* Basic implementation of the OSS Credentials interface that allows callers to
* pass in the OSS Access Key Id and OSS Secret Access Key in the constructor.
*/
class StaticCredentialsProvider implements CredentialsProvider
{
/**
* @var Credentials
*/
private $credentials;
/**
* Constructs a new StaticCredentialsProvider object, with the specified OSS
* access key and OSS secret key
*
* @param string $key OSS access key ID
* @param string $secret OSS access key secret
* @param string $token Security token to use
*/
public function __construct($key, $secret, $token = null)
{
$this->credentials = new Credentials($key, $secret, $token);
}
/**
* @return Credentials
*/
public function getCredentials()
{
return $this->credentials;
}
}

View File

@ -713,6 +713,8 @@ class RequestCore
$temp_headers[] = $k . ': ' . $v;
}
// fix "Expect: 100-continue"
$temp_headers[] = 'Expect:';
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $temp_headers);
}
@ -775,7 +777,7 @@ class RequestCore
* data stored in the `curl_handle` and `response` properties unless replacement data is passed in via
* parameters.
*
* @param resource $curl_handle (Optional) The reference to the already executed cURL request.
* @param resource|\CurlHandle|null|false $curl_handle (Optional) The reference to the already executed cURL request. Receive CurlHandle instance from PHP8.0
* @param string $response (Optional) The actual response content itself that needs to be parsed.
* @return ResponseCore A <ResponseCore> object containing a parsed HTTP response.
*/
@ -786,8 +788,8 @@ class RequestCore
$this->response = $response;
}
// As long as this came back as a valid resource...
if (is_resource($curl_handle)) {
// As long as this came back as a valid resource or CurlHandle instance...
if (is_resource($curl_handle) || (is_object($curl_handle) && in_array(get_class($curl_handle),array('CurlHandle','Swoole\Curl\Handler', 'Swoole\Coroutine\Curl\Handle'),true))) {
// Determine what's what.
$header_size = curl_getinfo($curl_handle, CURLINFO_HEADER_SIZE);
$this->response_headers = substr($this->response, 0, $header_size);
@ -842,12 +844,13 @@ class RequestCore
$this->response = curl_exec($curl_handle);
if ($this->response === false) {
throw new RequestCore_Exception('cURL resource: ' . (string)$curl_handle . '; cURL error: ' . curl_error($curl_handle) . ' (' . curl_errno($curl_handle) . ')');
throw new RequestCore_Exception('cURL error: ' . curl_error($curl_handle) . ' (' . curl_errno($curl_handle) . ')');
}
$parsed_response = $this->process_response($curl_handle, $this->response);
curl_close($curl_handle);
unset($curl_handle);
if ($parse) {
return $parsed_response;

View File

@ -11,20 +11,20 @@ namespace OSS\Model;
*/
class BucketInfo
{
/**
/**
* BucketInfo constructor.
*
* @param string $location
* @param string $name
* @param string $createDate
*/
public function __construct($location, $name, $createDate)
public function __construct($location = '', $name = '', $createDate = '')
{
$this->location = $location;
$this->name = $name;
$this->createDate = $createDate;
$this->name = $name;
}
/**
* Get bucket location
*
@ -55,6 +55,82 @@ class BucketInfo
return $this->createDate;
}
/**
* Get bucket storage class.
*
* @return string
*/
public function getStorageClass()
{
return $this->storageClass;
}
/**
* Get bucket extranet endpoint.
*
* @return string
*/
public function getExtranetEndpoint()
{
return $this->extranetEndpoint;
}
/**
* Get bucket intranet endpoint.
*
* @return string
*/
public function getIntranetEndpoint()
{
return $this->intranetEndpoint;
}
/**
* Get bucket intranet endpoint.
*
* @return string
*/
public function getRegion()
{
return $this->region;
}
/**
* Parse bucket information from node.
*
* @param xml $xml
* @throws OssException
* @return null
*/
public function parseFromXmlNode($xml)
{
if (isset($xml->Location)) {
$this->location = strval($xml->Location);
}
if (isset($xml->Name)) {
$this->name = strval($xml->Name);
}
if (isset($xml->CreationDate)) {
$this->createDate = strval($xml->CreationDate);
}
if (isset($xml->StorageClass)) {
$this->storageClass = strval($xml->StorageClass);
}
if (isset($xml->ExtranetEndpoint)) {
$this->extranetEndpoint = strval($xml->ExtranetEndpoint);
}
if (isset($xml->IntranetEndpoint)) {
$this->intranetEndpoint = strval($xml->IntranetEndpoint);
}
if (isset($xml->IntranetEndpoint)) {
$this->intranetEndpoint = strval($xml->IntranetEndpoint);
}
if (isset($xml->Region)) {
$this->region = strval($xml->Region);
}
}
/**
* bucket region
*
@ -75,4 +151,31 @@ class BucketInfo
*/
private $createDate;
/**
* bucket storage class
*
* @var string
*/
private $storageClass;
/**
* bucket extranet endpoint
*
* @var string
*/
private $extranetEndpoint;
/**
* bucket intranet endpoint
*
* @var string
*/
private $intranetEndpoint;
/**
* bucket region
*
* @var string
*/
private $region;
}

View File

@ -0,0 +1,331 @@
<?php
namespace OSS\Model;
/**
* Bucket stat class.
*
* Class BucketStat
* @package OSS\Model
*/
class BucketStat
{
/**
* Get storage
*
* @return int
*/
public function getStorage()
{
return $this->storage;
}
/**
* Get object count
*
* @return int
*/
public function getObjectCount()
{
return $this->objectCount;
}
/**
* Get multipart upload count.
*
* @return int
*/
public function getMultipartUploadCount()
{
return $this->multipartUploadCount;
}
/**
* Get live channel count
*
* @return int
*/
public function getLiveChannelCount()
{
return $this->liveChannelCount;
}
/**
* Get last modified time
*
* @return int
*/
public function getLastModifiedTime()
{
return $this->lastModifiedTime;
}
/**
* Get standard storage
*
* @return int
*/
public function getStandardStorage()
{
return $this->standardStorage;
}
/**
* Get standard object count
*
* @return int
*/
public function getStandardObjectCount()
{
return $this->standardObjectCount;
}
/**
* Get infrequent access storage
*
* @return int
*/
public function getInfrequentAccessStorage()
{
return $this->infrequentAccessStorage;
}
/**
* Get infrequent access real storage
*
* @return int
*/
public function getInfrequentAccessRealStorage()
{
return $this->infrequentAccessRealStorage;
}
/**
* Get infrequent access object count
*
* @return int
*/
public function getInfrequentAccessObjectCount()
{
return $this->infrequentAccessObjectCount;
}
/**
* Get archive storage
*
* @return int
*/
public function getArchiveStorage()
{
return $this->archiveStorage;
}
/**
* Get archive real storage
*
* @return int
*/
public function getArchiveRealStorage()
{
return $this->archiveRealStorage;
}
/**
* Get archive object count
*
* @return int
*/
public function getArchiveObjectCount()
{
return $this->archiveObjectCount;
}
/**
* Get cold archive storage
*
* @return int
*/
public function getColdArchiveStorage()
{
return $this->coldArchiveStorage;
}
/**
* Get cold archive real storage
*
* @return int
*/
public function getColdArchiveRealStorage()
{
return $this->coldArchiveRealStorage;
}
/**
* Get cold archive object count
*
* @return int
*/
public function getColdArchiveObjectCount()
{
return $this->coldArchiveObjectCount;
}
/**
* Parse stat from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (isset($xml->Storage) ) {
$this->storage = intval($xml->Storage);
}
if (isset($xml->ObjectCount) ) {
$this->objectCount = intval($xml->ObjectCount);
}
if (isset($xml->MultipartUploadCount) ) {
$this->multipartUploadCount = intval($xml->MultipartUploadCount);
}
if (isset($xml->LiveChannelCount) ) {
$this->liveChannelCount = intval($xml->LiveChannelCount);
}
if (isset($xml->LastModifiedTime) ) {
$this->lastModifiedTime = intval($xml->LastModifiedTime);
}
if (isset($xml->StandardStorage) ) {
$this->standardStorage = intval($xml->StandardStorage);
}
if (isset($xml->StandardObjectCount) ) {
$this->standardObjectCount = intval($xml->StandardObjectCount);
}
if (isset($xml->InfrequentAccessStorage) ) {
$this->infrequentAccessStorage = intval($xml->InfrequentAccessStorage);
}
if (isset($xml->InfrequentAccessRealStorage) ) {
$this->infrequentAccessRealStorage = intval($xml->InfrequentAccessRealStorage);
}
if (isset($xml->InfrequentAccessObjectCount) ) {
$this->infrequentAccessObjectCount = intval($xml->InfrequentAccessObjectCount);
}
if (isset($xml->ArchiveStorage) ) {
$this->archiveStorage = intval($xml->ArchiveStorage);
}
if (isset($xml->ArchiveRealStorage) ) {
$this->archiveRealStorage = intval($xml->ArchiveRealStorage);
}
if (isset($xml->ArchiveObjectCount) ) {
$this->archiveObjectCount = intval($xml->ArchiveObjectCount);
}
if (isset($xml->ColdArchiveStorage) ) {
$this->coldArchiveStorage = intval($xml->ColdArchiveStorage);
}
if (isset($xml->ColdArchiveRealStorage) ) {
$this->coldArchiveRealStorage = intval($xml->ColdArchiveRealStorage);
}
if (isset($xml->ColdArchiveObjectCount) ) {
$this->coldArchiveObjectCount = intval($xml->ColdArchiveObjectCount);
}
}
/**
* current storage
*
* @var int
*/
private $storage;
/**
* object count
*
* @var int
*/
private $objectCount;
/**
* multipart upload count
*
* @var int
*/
private $multipartUploadCount;
/**
* live channel count
* @var int
*/
private $liveChannelCount;
/**
* last modified time
* @var int
*/
private $lastModifiedTime;
/**
* standard storage
* @var int
*/
private $standardStorage;
/**
* standard object count
* @var int
*/
private $standardObjectCount;
/**
* infrequent access storage
* @var int
*/
private $infrequentAccessStorage;
/**
* infrequent access real storage
* @var int
*/
private $infrequentAccessRealStorage;
/**
* infrequent access object Count
* @var int
*/
private $infrequentAccessObjectCount;
/**
* archive storage
* @var int
*/
private $archiveStorage;
/**
* archive real storage
* @var int
*/
private $archiveRealStorage;
/**
* archive object count
* @var int
*/
private $archiveObjectCount;
/**
* cold archive storage
* @var int
*/
private $coldArchiveStorage;
/**
* cold archive real storage
* @var int
*/
private $coldArchiveRealStorage;
/**
* cold archive object count
* @var int
*/
private $coldArchiveObjectCount;
}

View File

@ -0,0 +1,105 @@
<?php
namespace OSS\Model;
/**
* Cname token info class.
*
* Class CnameTokenInfo
* @package OSS\Model
*/
class CnameTokenInfo
{
/**
* Get bucket name
*
* @return string
*/
public function getBucket()
{
return $this->bucket;
}
/**
* Get cname
*
* @return string
*/
public function getCname()
{
return $this->cname;
}
/**
* Get token.
*
* @return string
*/
public function getToken()
{
return $this->token;
}
/**
* Get expireTime.
*
* @return string
*/
public function getExpireTime()
{
return $this->expireTime;
}
/**
* Parse cname token from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (isset($xml->Bucket) ) {
$this->bucket = strval($xml->Bucket);
}
if (isset($xml->Cname) ) {
$this->cname = strval($xml->Cname);
}
if (isset($xml->Token) ) {
$this->token = strval($xml->Token);
}
if (isset($xml->ExpireTime) ) {
$this->expireTime = strval($xml->ExpireTime);
}
}
/**
* bucket name
*
* @var string
*/
private $bucket;
/**
* cname
*
* @var string
*/
private $cname;
/**
* token
*
* @var string
*/
private $token;
/**
* expire time
*
* @var string
*/
private $expireTime;
}

View File

@ -0,0 +1,65 @@
<?php
namespace OSS\Model;
/**
*
* Class DeleteMarkerInfo
*
* @package OSS\Model
*/
class DeleteMarkerInfo
{
/**
* DeleteMarkerInfo constructor.
*
* @param string $key
* @param string $versionId
* @param string $lastModified
* @param string $isLatest
*/
public function __construct($key, $versionId, $lastModified, $isLatest)
{
$this->key = $key;
$this->versionId = $versionId;
$this->lastModified = $lastModified;
$this->isLatest = $isLatest;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getVersionId()
{
return $this->versionId;
}
/**
* @return string
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* @return string
*/
public function getIsLatest()
{
return $this->isLatest;
}
private $key = "";
private $versionId = "";
private $lastModified = "";
private $isLatest = "";
}

View File

@ -0,0 +1,41 @@
<?php
namespace OSS\Model;
/**
* Class DeleteObjectInfo
* @package OSS\Model
*/
class DeleteObjectInfo
{
/**
* DeleteObjectInfo constructor.
*
* @param string $key
* @param string $versionId
*/
public function __construct($key, $versionId = '')
{
$this->key = $key;
$this->versionId = $versionId;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getVersionId()
{
return $this->versionId;
}
private $key = "";
private $versionId = "";
}

View File

@ -0,0 +1,63 @@
<?php
namespace OSS\Model;
/**
* Class DeletedObjectInfo
* @package OSS\Model
*/
class DeletedObjectInfo
{
/**
* DeletedObjectInfo constructor.
*
* @param string $key
* @param string $versionId
* @param string $deleteMarker
* @param string $deleteMarkerVersionId
*/
public function __construct($key, $versionId, $deleteMarker, $deleteMarkerVersionId)
{
$this->key = $key;
$this->versionId = $versionId;
$this->deleteMarker = $deleteMarker;
$this->deleteMarkerVersionId = $deleteMarkerVersionId;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getVersionId()
{
return $this->versionId;
}
/**
* @return string
*/
public function getDeleteMarker()
{
return $this->deleteMarker;
}
/**
* @return string
*/
public function getDeleteMarkerVersionId()
{
return $this->deleteMarkerVersionId;
}
private $key = "";
private $versionId = "";
private $deleteMarker = "";
private $deleteMarkerVersionId = "";
}

View File

@ -0,0 +1,64 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class ExtendWormConfig
* @package OSS\Model
*
*/
class ExtendWormConfig implements XmlConfig
{
/**
* ExtendWormConfig constructor.
* @param null $day
*/
public function __construct($day = null)
{
$this->day = $day;
}
/**
* Parse ExtendWormConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
throw new OssException("Not implemented.");
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><ExtendWormConfiguration></ExtendWormConfiguration>');
if (isset($this->day)) {
$xml->addChild('RetentionPeriodInDays', $this->day);
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return int
*/
public function getDay()
{
return $this->day;
}
private $day = 0;
}

View File

@ -1,6 +1,9 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class GetLiveChannelHistory
* @package OSS\Model

View File

@ -0,0 +1,64 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class InitiateWormConfig
* @package OSS\Model
*
*/
class InitiateWormConfig implements XmlConfig
{
/**
* InitiateWormConfig constructor.
* @param null $day
*/
public function __construct($day = null)
{
$this->day = $day;
}
/**
* Parse InitiateWormConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
throw new OssException("Not implemented.");
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><InitiateWormConfiguration></InitiateWormConfiguration>');
if (isset($this->day)) {
$xml->addChild('RetentionPeriodInDays', $this->day);
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return int
*/
public function getDay()
{
return $this->day;
}
private $day = 0;
}

View File

@ -1,7 +1,6 @@
<?php
namespace OSS\Model;
/**
*
* Class ObjectInfo
@ -23,7 +22,7 @@ class ObjectInfo
* @param string $lastModified
* @param string $eTag
* @param string $type
* @param int $size
* @param string $size
* @param string $storageClass
*/
public function __construct($key, $lastModified, $eTag, $type, $size, $storageClass)
@ -67,15 +66,26 @@ class ObjectInfo
{
return $this->type;
}
/**
* php7 && 64bit can use it
* @return int
*/
public function getSize()
{
return (int)$this->size;
}
/**
* php5.x or 32bit must use it
* @return string
*/
public function getSizeStr()
{
return $this->size;
}
/**
* @return string
*/
@ -88,6 +98,6 @@ class ObjectInfo
private $lastModified = "";
private $eTag = "";
private $type = "";
private $size = 0;
private $size = "0";
private $storageClass = "";
}

View File

@ -0,0 +1,147 @@
<?php
namespace OSS\Model;
/**
* Class ObjectListInfoV2
*
* The class of return value of ListObjectsV2
*
* @package OSS\Model
*/
class ObjectListInfoV2
{
/**
* ObjectListInfoV2 constructor.
*
* @param string $bucketName
* @param string $prefix
* @param int $maxKeys
* @param string $delimiter
* @param null $isTruncated
* @param array $objectList
* @param array $prefixList
* @param string $continuationToken
* @param string $nextContinuationToken
* @param string $startAfter
* @param int $keyCount
*/
public function __construct($bucketName, $prefix, $maxKeys, $delimiter, $isTruncated, array $objectList, array $prefixList, $continuationToken, $nextContinuationToken, $startAfter, $keyCount)
{
$this->bucketName = $bucketName;
$this->prefix = $prefix;
$this->maxKeys = $maxKeys;
$this->delimiter = $delimiter;
$this->isTruncated = $isTruncated;
$this->objectList = $objectList;
$this->prefixList = $prefixList;
$this->continuationToken = $continuationToken;
$this->nextContinuationToken = $nextContinuationToken;
$this->startAfter = $startAfter;
$this->keyCount = $keyCount;
}
/**
* @return string
*/
public function getBucketName()
{
return $this->bucketName;
}
/**
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* @return int
*/
public function getMaxKeys()
{
return $this->maxKeys;
}
/**
* @return string
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* @return mixed
*/
public function getIsTruncated()
{
return $this->isTruncated;
}
/**
* Get the ObjectInfo list.
*
* @return ObjectInfo[]
*/
public function getObjectList()
{
return $this->objectList;
}
/**
* Get the PrefixInfo list
*
* @return PrefixInfo[]
*/
public function getPrefixList()
{
return $this->prefixList;
}
/**
* @return string
*/
public function getContinuationToken()
{
return $this->continuationToken;
}
/**
* @return string
*/
public function getNextContinuationToken()
{
return $this->nextContinuationToken;
}
/**
* @return string
*/
public function getStartAfter()
{
return $this->startAfter;
}
/**
* @return int
*/
public function getKeyCount()
{
return $this->keyCount;
}
private $bucketName = "";
private $prefix = "";
private $maxKeys = 0;
private $delimiter = "";
private $isTruncated = null;
private $objectList = array();
private $prefixList = array();
private $nextContinuationToken = "";
private $continuationToken = "";
private $startAfter = "";
private $keyCount = 0;
}

View File

@ -0,0 +1,125 @@
<?php
namespace OSS\Model;
/**
*
* Class ObjectVersionInfo
*
* The element type of ObjectVersionListInfo, which is the return value type of listObjectVersions
*
* The return value of listObjectVersions includes three arrays
* One is the returned ObjectVersionListInfo, which is similar to a file list in a file system.
* The other is the returned prefix list, which is similar to a folder list in a file system.
*
* @package OSS\Model
*/
class ObjectVersionInfo
{
/**
* ObjectVersionInfo constructor.
*
* @param string $key
* @param string $lastModified
* @param string $eTag
* @param string $type
* @param string $size
* @param string $storageClass
* @param string $isLatest
*/
public function __construct($key, $versionId, $lastModified, $eTag, $type, $size, $storageClass, $isLatest)
{
$this->key = $key;
$this->versionId = $versionId;
$this->lastModified = $lastModified;
$this->eTag = $eTag;
$this->type = $type;
$this->size = $size;
$this->storageClass = $storageClass;
$this->isLatest = $isLatest;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getVersionId()
{
return $this->versionId;
}
/**
* @return string
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* @return string
*/
public function getETag()
{
return $this->eTag;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* php7 && 64bit can use it
* @return int
*/
public function getSize()
{
return (int)$this->size;
}
/**
* php5.x or 32bit must use it
* @return string
*/
public function getSizeStr()
{
return $this->size;
}
/**
* @return string
*/
public function getStorageClass()
{
return $this->storageClass;
}
/**
* @return string
*/
public function getIsLatest()
{
return $this->isLatest;
}
private $key = "";
private $versionId = "";
private $lastModified = "";
private $eTag = "";
private $type = "";
private $size = "0";
private $storageClass = "";
private $isLatest = "";
}

View File

@ -0,0 +1,162 @@
<?php
namespace OSS\Model;
/**
* Class ObjectVersionListInfo
*
* The class of return value of ListObjectVersions
*
* @package OSS\Model
*/
class ObjectVersionListInfo
{
/**
* ObjectVersionListInfo constructor.
*
* @param string $bucketName
* @param string $prefix
* @param string $keyMarker
* @param string $nextKeyMarker
* @param string $versionIdMarker
* @param string $nextVersionIdMarker
* @param string $maxKeys
* @param string $delimiter
* @param null $isTruncated
* @param array $objectversionList
* @param array $deleteMarkerList
* @param array $prefixList
*/
public function __construct($bucketName, $prefix, $keyMarker, $nextKeyMarker, $versionIdMarker, $nextVersionIdMarker
, $maxKeys, $delimiter, $isTruncated
, array $objectversionList, array $deleteMarkerList, array $prefixList)
{
$this->bucketName = $bucketName;
$this->prefix = $prefix;
$this->keyMarker = $keyMarker;
$this->nextKeyMarker = $nextKeyMarker;
$this->versionIdMarker = $versionIdMarker;
$this->nextVersionIdMarker = $nextVersionIdMarker;
$this->maxKeys = $maxKeys;
$this->delimiter = $delimiter;
$this->isTruncated = $isTruncated;
$this->objectVersionList = $objectversionList;
$this->deleteMarkerList = $deleteMarkerList;
$this->prefixList = $prefixList;
}
/**
* @return string
*/
public function getBucketName()
{
return $this->bucketName;
}
/**
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* @return string
*/
public function getKeyMarker()
{
return $this->keyMarker;
}
/**
* @return string
*/
public function getNextKeyMarker()
{
return $this->nextKeyMarker;
}
/**
* @return string
*/
public function getVersionIdMarker()
{
return $this->versionIdMarker;
}
/**
* @return string
*/
public function getNextVersionIdMarker()
{
return $this->nextVersionIdMarker;
}
/**
* @return int
*/
public function getMaxKeys()
{
return $this->maxKeys;
}
/**
* @return string
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* @return mixed
*/
public function getIsTruncated()
{
return $this->isTruncated;
}
/**
* Get the ObjectVersionInfo list.
*
* @return ObjectVersionInfo[]
*/
public function getObjectVersionList()
{
return $this->objectVersionList;
}
/**
* Get the DeleteMarkerInfo list.
*
* @return DeleteMarkerInfo[]
*/
public function getDeleteMarkerList()
{
return $this->deleteMarkerList;
}
/**
* Get the PrefixInfo list
*
* @return PrefixInfo[]
*/
public function getPrefixList()
{
return $this->prefixList;
}
private $bucketName = "";
private $prefix = "";
private $keyMarker = "";
private $nextKeyMarker = "";
private $versionIdmarker = "";
private $nextVersionIdMarker = "";
private $maxKeys = 0;
private $delimiter = "";
private $isTruncated = null;
private $objectVersionList = array();
private $deleteMarkerList = array();
private $prefixList = array();
}

View File

@ -14,7 +14,7 @@ class PartInfo
* @param int $partNumber
* @param string $lastModified
* @param string $eTag
* @param int $size
* @param string $size
*/
public function __construct($partNumber, $lastModified, $eTag, $size)
{
@ -49,15 +49,26 @@ class PartInfo
}
/**
* php7 && 64bit can use it
* @return int
*/
public function getSize()
{
return $this->size;
return (int)$this->size;
}
/**
* php5.x or 32bit must use it
* @return string
*/
public function getSizeStr()
{
return $this->size;
}
private $partNumber = 0;
private $lastModified = "";
private $eTag = "";
private $size = 0;
private $size = "0";
}

View File

@ -0,0 +1,68 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class RequestPaymentConfig
* @package OSS\Model
*
* @link https://help.aliyun.com/document_detail/117914.htm
*/
class RequestPaymentConfig implements XmlConfig
{
/**
* RequestPaymentConfig constructor.
* @param null $payer
*/
public function __construct($payer = null)
{
$this->payer = $payer;
}
/**
* Parse ServerSideEncryptionConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (isset($xml->Payer)) {
$this->payer = strval($xml->Payer);
}
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><RequestPaymentConfiguration></RequestPaymentConfiguration>');
if (isset($this->payer)) {
$xml->addChild('Payer', $this->payer);
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return string
*/
public function getPayer()
{
return $this->payer;
}
private $payer = "";
}

View File

@ -0,0 +1,77 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class RestoreConfig
* @package OSS\Model
*
*/
class RestoreConfig implements XmlConfig
{
/**
* RestoreConfig constructor.
* @param int $day
* @param null $tier
*/
public function __construct($day, $tier = null)
{
$this->day = $day;
$this->tier = $tier;
}
/**
* Parse RestoreConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
throw new OssException("Not implemented.");
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><RestoreRequest></RestoreRequest>');
$xml->addChild('Days', strval($this->day));
if (isset($this->tier)) {
$xml_param = $xml->addChild('JobParameters');
$xml_param->addChild('Tier', $this->tier);
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return int
*/
public function getDay()
{
return $this->day;
}
/**
* @return string
*/
public function getTier()
{
return $this->tier;
}
private $day = 1;
private $tier = 'Standard';
}

View File

@ -0,0 +1,91 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class ServerSideEncryptionConfig
* @package OSS\Model
*
* @link https://help.aliyun.com/document_detail/117914.htm
*/
class ServerSideEncryptionConfig implements XmlConfig
{
/**
* ServerSideEncryptionConfig constructor.
* @param null $sseAlgorithm
* @param null $kmsMasterKeyID
*/
public function __construct($sseAlgorithm = null, $kmsMasterKeyID = null)
{
$this->sseAlgorithm = $sseAlgorithm;
$this->kmsMasterKeyID = $kmsMasterKeyID;
}
/**
* Parse ServerSideEncryptionConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (!isset($xml->ApplyServerSideEncryptionByDefault)) return;
foreach ($xml->ApplyServerSideEncryptionByDefault as $default) {
foreach ($default as $key => $value) {
if ($key === 'SSEAlgorithm') {
$this->sseAlgorithm = strval($value);
} elseif ($key === 'KMSMasterKeyID') {
$this->kmsMasterKeyID = strval($value);
}
}
break;
}
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><ServerSideEncryptionRule></ServerSideEncryptionRule>');
$default = $xml->addChild('ApplyServerSideEncryptionByDefault');
if (isset($this->sseAlgorithm)) {
$default->addChild('SSEAlgorithm', $this->sseAlgorithm);
}
if (isset($this->kmsMasterKeyID)) {
$default->addChild('KMSMasterKeyID', $this->kmsMasterKeyID);
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return string
*/
public function getSSEAlgorithm()
{
return $this->sseAlgorithm;
}
/**
* @return string
*/
public function getKMSMasterKeyID()
{
return $this->kmsMasterKeyID;
}
private $sseAlgorithm = "";
private $kmsMasterKeyID = "";
}

View File

@ -2,6 +2,8 @@
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class StorageCapacityConfig
*

View File

@ -0,0 +1,41 @@
<?php
namespace OSS\Model;
/**
* Class Tag
* @package OSS\Model
*/
class Tag
{
/**
* Tag constructor.
*
* @param string $key
* @param string $value
*/
public function __construct($key, $value)
{
$this->key = $key;
$this->value = $value;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
private $key = "";
private $value = "";
}

View File

@ -0,0 +1,89 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class TaggingConfig
* @package OSS\Model
*
*/
class TaggingConfig implements XmlConfig
{
/**
* TaggingConfig constructor.
*/
public function __construct()
{
$this->tags = array();
}
/**
* Get Tag list
*
* @return Tag[]
*/
public function getTags()
{
return $this->tags;
}
/**
* Add a new Tag
*
* @param Tag $tag
* @throws OssException
*/
public function addTag($tag)
{
$this->tags[] = $tag;
}
/**
* Parse TaggingConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (!isset($xml->TagSet) || !isset($xml->TagSet->Tag)) return;
foreach ($xml->TagSet->Tag as $tag) {
$this->addTag(new Tag($tag->Key, $tag->Value));
}
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><Tagging></Tagging>');
$xmlTagSet = $xml->addChild('TagSet');
foreach ($this->tags as $tag) {
$xmlTag = $xmlTagSet->addChild('Tag');
$xmlTag->addChild('Key', strval($tag->getKey()));
$xmlTag->addChild('Value', strval($tag->getValue()));
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* Tag list
*
* @var Tag[]
*/
private $tags = array();
}

View File

@ -0,0 +1,73 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class TransferAccelerationConfig
* @package OSS\Model
*/
class TransferAccelerationConfig implements XmlConfig
{
/**
* Parse TransferAccelerationConfig from the xml.
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (isset($xml->Enabled)) {
$this->enabled = (strval($xml->Enabled) === 'TRUE' || strval($xml->Enabled) === 'true') ? true : false;
}
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><TransferAccelerationConfiguration></TransferAccelerationConfiguration>');
if (isset($this->enabled)) {
if($this->enabled === true){
$xml->addChild('Enabled','true');
} else {
$xml->addChild('Enabled','false');
}
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return bool
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* @param boolean enabled
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
}
/**
* @var $enabled boolean
*/
private $enabled = false;
}

View File

@ -0,0 +1,67 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class VersioningConfig
* @package OSS\Model
*
*/
class VersioningConfig implements XmlConfig
{
/**
* VersioningConfig constructor.
* @param null $status
*/
public function __construct($status = null)
{
$this->status = $status;
}
/**
* Parse VersioningConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (isset($xml->Status)) {
$this->status = strval($xml->Status);
}
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><VersioningConfiguration></VersioningConfiguration>');
if (isset($this->status)) {
$xml->addChild('Status', $this->status);
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return string
*/
public function getStatus()
{
return $this->status;
}
private $status = "";
}

View File

@ -0,0 +1,90 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class WormConfig
* @package OSS\Model
*
*/
class WormConfig implements XmlConfig
{
/**
* Parse WormConfig from the xml.
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (isset($xml->WormId)) {
$this->wormId = strval($xml->WormId);
}
if (isset($xml->State)) {
$this->state = strval($xml->State);
}
if (isset($xml->RetentionPeriodInDays)) {
$this->day = intval($xml->RetentionPeriodInDays);
}
if (isset($xml->CreationDate)) {
$this->creationDate = strval($xml->CreationDate);
}
}
/**
* Serialize the object into xml string.
*
* @return string
*/
public function serializeToXml()
{
throw new OssException("Not implemented.");
}
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return string
*/
public function getWormId()
{
return $this->wormId;
}
/**
* @return string
*/
public function getState()
{
return $this->state;
}
/**
* @return int
*/
public function getDay()
{
return $this->day;
}
/**
* @return string
*/
public function getCreationDate()
{
return $this->creationDate;
}
private $wormId = '';
private $state = '';
private $creationDate = '';
private $day = 0;
}

File diff suppressed because it is too large Load Diff

View File

@ -25,6 +25,6 @@ class CopyObjectResult extends Result
$result[] = $xml->ETag;
}
return $result;
return array_merge($result, $this->rawResponse->header);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace OSS\Result;
use OSS\Model\CnameTokenInfo;
class CreateBucketCnameTokenResult extends Result
{
/**
* @return CnameConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$info = new CnameTokenInfo();
$info->parseFromXml($content);
return $info;
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace OSS\Result;
use OSS\Core\OssUtil;
use OSS\Model\DeletedObjectInfo;
/**
* Class DeleteObjectVersionsResult
* @package OSS\Result
*/
class DeleteObjectVersionsResult extends Result
{
/**
* @return DeletedObjectInfo[]
*/
protected function parseDataFromResponse()
{
$xml = simplexml_load_string($this->rawResponse->body);
$encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : "";
return $this->parseDeletedList($xml, $encodingType);
}
private function parseDeletedList($xml, $encodingType)
{
$retList = array();
if (isset($xml->Deleted)) {
foreach ($xml->Deleted as $content) {
$key = isset($content->Key) ? strval($content->Key) : "";
$key = OssUtil::decodeKey($key, $encodingType);
$versionId = isset($content->VersionId) ? strval($content->VersionId) : "";
$deleteMarker = isset($content->DeleteMarker) ? strval($content->DeleteMarker) : "";
$deleteMarkerVersionId = isset($content->DeleteMarkerVersionId) ? strval($content->DeleteMarkerVersionId) : "";
$retList[] = new DeletedObjectInfo($key, $versionId, $deleteMarker, $deleteMarkerVersionId);
}
}
return $retList;
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace OSS\Result;
use OSS\Model\CnameTokenInfo;
class GetBucketCnameTokenResult extends Result
{
/**
* @return CnameConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$info = new CnameTokenInfo();
$info->parseFromXml($content);
return $info;
}
}

Some files were not shown because too many files have changed in this diff Show More