Completed
Pull Request — master (#319)
by
unknown
24:29
created

BucketManager::updateBucketEvent()   C

Complexity

Conditions 9
Paths 256

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
nc 256
nop 8
dl 0
loc 39
ccs 0
cts 28
cp 0
crap 90
rs 6.5137
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
namespace Qiniu\Storage;
3
4
use Qiniu\Auth;
5
use Qiniu\Config;
6
use Qiniu\Zone;
7
use Qiniu\Http\Client;
8
use Qiniu\Http\Error;
9
10
/**
11
 * 主要涉及了空间资源管理及批量操作接口的实现,具体的接口规格可以参考
12
 *
13
 * @link https://developer.qiniu.com/kodo/api/1274/rs
14
 */
15
final class BucketManager
16
{
17
    private $auth;
18
    private $config;
19
20 42
    public function __construct(Auth $auth, Config $config = null)
21
    {
22 42
        $this->auth = $auth;
23 42
        if ($config == null) {
24 42
            $this->config = new Config();
25 42
        } else {
26
            $this->config = $config;
27
        }
28 42
    }
29
30
    /**
31
     * 获取指定账号下所有的空间名。
32
     *
33
     * @return string[] 包含所有空间名
34
     */
35 3
    public function buckets($shared = true)
36
    {
37 3
        $includeShared = "false";
38 3
        if ($shared === true) {
39 3
            $includeShared = "true";
40 3
        }
41 3
        return $this->rsGet('/buckets?shared=' . $includeShared);
42
    }
43
44
    /**
45
     * 列举空间,返回bucket列表
46
     * region 指定区域,global 指定全局空间。
47
     * 在指定了 region 参数时,
48
     * 如果指定 global 为 true,那么忽略 region 参数指定的区域,返回所有区域的全局空间。
49
     * 如果没有指定 global 为 true,那么返回指定区域中非全局空间。
50
     * 在没有指定 region 参数时(包括指定为空""),
51
     * 如果指定 global 为 true,那么返回所有区域的全局空间。
52
     * 如果没有指定 global 为 true,那么返回指定区域中所有的空间,包括全局空间。
53
     * 在指定了line为 true 时,只返回 Line 空间;否则,只返回非 Line 空间。
54
     * share 参数用于指定共享空间。
55
     */
56
57
    public function listbuckets(
58
        $region = null,
59
        $line = 'false',
60
        $shared = 'false'
61
    ) {
62
        $path = '/v3/buckets?region=' . $region . '&line=' . $line . '&shared=' . $shared;
63
        $info = $this->ucPost($path);
64
        return $info;
65
    }
66
67
    /**
68
     * 创建空间
69
     *
70
     * @param $name     创建的空间名
71
     * BucketName不满足以上要求返回400 (the specified bucket is not valid)
72
     * 如果BucketName已经被使用,返回614(bucket exists)
73
     * @param $region    创建的区域,默认华东
74
     * 
75
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
76
     */
77
    
78
    public function createBucket($name, $region = 'z0')
79
    {
80
        $path = '/mkbucketv3/'.$name.'/region/' . $region;
81
        return $this->rsPost($path, null);
82
    }
83
84
    /**
85
     * 删除空间
86
     *
87
     * @param $name     删除的空间名
88
     *
89
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
90
     */
91
    public function deleteBucket($name)
92
    {
93
        $path = '/drop/'.$name;
94
        return $this->rsPost($path, null);
95
    }
96
97
    /**
98
     * 获取指定空间绑定的所有的域名
99
     *
100
     * @return string[] 包含所有空间域名
101
     */
102
    public function domains($bucket)
103
    {
104
        return $this->apiGet('/v6/domain/list?tbl=' . $bucket);
105
    }
106
107
    /**
108
     * 获取指定空间的相关信息
109
     *
110
     * @return string[] 包含空间信息
111
     */
112
    public function bucketInfo($bucket)
113
    {
114
        $path = '/v2/bucketInfo?bucket=' . $bucket;
115
        $info = $this->ucPost($path);
116
        return $info;
117
    }
118
119
    /**
120
     * 获取指定zone的空间信息列表
121
     * 在Region 未指定且Global 不为 true 时(包含未指定的情况,下同),返回用户的所有空间。
122
     * 在指定了 region 参数且 global 不为 true 时,只列举非全局空间。
123
     * shared 不指定shared参数或指定shared为rw或false时,返回包含具有读写权限空间,
124
     * 指定shared为rd或true时,返回包含具有读权限空间。
125
     * fs:如果为 true,会返回每个空间当前的文件数和存储量(实时数据)。
126
     * @return string[] 包含空间信息
127
     */
128
    public function bucketInfos($region = null, $shared = 'false', $fs = 'false')
129
    {
130
        $path = '/v2/bucketInfos?region=' . $region . '&shared=' . $shared . '&fs=' . $fs;
131
        $info = $this->ucPost($path);
132
        return $info;
133
    }
134
135
    /**
136
     * 获取空间绑定的域名列表
137
     * @return string[] 包含空间绑定的所有域名
138
     */
139
140
    /**
141
     * 列取空间的文件列表
142
     *
143
     * @param $bucket     空间名
144
     * @param $prefix     列举前缀
145
     * @param $marker     列举标识符
146
     * @param $limit      单次列举个数限制
147
     * @param $delimiter  指定目录分隔符
148
     *
149
     * @return array    包含文件信息的数组,类似:[
150
*                                              {
151
*                                                 "hash" => "<Hash string>",
152
*                                                  "key" => "<Key string>",
153
*                                                  "fsize" => "<file size>",
154
*                                                  "putTime" => "<file modify time>"
155
*                                              },
156
*                                              ...
157 3
*                                            ]
158
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
159
     */
160
    public function listFiles(
161
        $bucket,
162
        $prefix = null,
163
        $marker = null,
164 3
        $limit = 1000,
165 3
        $delimiter = null
166 3
    ) {
167 3
        $query = array('bucket' => $bucket);
168 3
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
169 3
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
170 3
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
171
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
172
        $url = $this->getRsfHost() . '/list?' . http_build_query($query);
173
        return $this->get($url);
174
    }
175
176
    /**
177
     * 列取空间的文件列表
178
     *
179
     * @param $bucket     空间名
180
     * @param $prefix     列举前缀
181
     * @param $marker     列举标识符
182
     * @param $limit      单次列举个数限制
183
     * @param $delimiter  指定目录分隔符
184
     * @param $skipconfirm  是否跳过已删除条目的确认机制
185
     *
186
     * @return array    包含文件信息的数组,类似:[
187
*                                              {
188
*                                                 "hash" => "<Hash string>",
189
*                                                  "key" => "<Key string>",
190
*                                                  "fsize" => "<file size>",
191
*                                                  "putTime" => "<file modify time>"
192
*                                              },
193
*                                              ...
194
*                                            ]
195
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
196
     */
197
    public function listFilesv2(
198
        $bucket,
199
        $prefix = null,
200
        $marker = null,
201
        $limit = 1000,
202
        $delimiter = null,
203
        $skipconfirm = true
204
    ) {
205
        $query = array('bucket' => $bucket);
206
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
207
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
208
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
209
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
210
        \Qiniu\setWithoutEmpty($query, 'skipconfirm', $skipconfirm);
211
        $path = '/v2/list?' . http_build_query($query);
212
        $url = $this->getRsfHost() . $path;
213
        $headers = $this->auth->authorization($url, null, 'application/x-www-form-urlencoded');
214
        $ret = Client::post($url, null, $headers);
215
        if (!$ret->ok()) {
216
            return array(null, new Error($url, $ret));
217
        }
218
        $r = explode("\n", $ret->body);
219
        $pop = array_pop($r);
0 ignored issues
show
Unused Code introduced by
$pop is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
220
        return array($r, null);
221
    }
222
223
    /**
224
     * 设置Referer防盗链
225
     *
226
     * @param $bucket     空间名
227
     * @param $mode     0: 表示关闭Referer(使用此选项将会忽略以下参数并将恢复默认值);
228
     * 1: 表示设置Referer白名单; 2:表示设置Referer黑名单
229
     * @param $norefer     0: 表示不允许空 Refer 访问; 1: 表示允许空 Refer 访问
230
     * @param $pattern      规则字符串, 当前允许格式分为三种: 一种为空主机头域名,
231
     * 比如 foo.com; 一种是泛域名,比如 *.bar.com; 一种是完全通配符,
232
     * 即一个 *; 多个规则之间用;隔开, 比如: foo.com;*.bar.com;sub.foo.com;*.sub.bar.com
233
     * @param $source_enabled  源站是否支持,默认为0只给CDN配置, 设置为1表示开启源站防盗链
234
     *
235
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
236
     */
237
    // public function referAntiLeech(){
238
239
    // }
240
241
    /**
242
     * 增加bucket生命规则
243
     *
244
     * @param $bucket     空间名
245
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,只能为
246
     * 字母、数字、下划线
247
     * @param $prefix     同一个 bucket 里面前缀不能重复
248
     * @param $delete_after_days      指定上传文件多少天后删除,指定为0表示不删除,
249
     * 大于0表示多少天后删除,需大于 to_line_after_days
250
     * @param $to_line_after_days  指定文件上传多少天后转低频存储。指定为0表示
251
     * 不转低频存储,小于0表示上传的文件立即变低频存储
252
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
253
     */
254
    public function bucketLifecycleRule(
255
        $bucket,
256
        $name,
257
        $prefix,
258
        $delete_after_days,
259
        $to_line_after_days
260
    ) {
261
        $path = '/rules/add';
262
        if ($bucket) {
263
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
264
        }
265
        if ($name) {
266
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
267
        }
268
        if ($prefix) {
269
            $params['prefix'] = $prefix;
270
        }
271
        if ($delete_after_days) {
272
            $params['delete_after_days'] = $delete_after_days;
273
        }
274
        if ($to_line_after_days) {
275
            $params['to_line_after_days'] = $to_line_after_days;
276
        }
277
        $data = http_build_query($params);
278
        $info = $this->ucPost($path, $data);
279
        return $info;
280
    }
281
282
    /**
283
     * 更新bucket生命规则
284
     *
285
     * @param $bucket     空间名
286
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,只能为字母、
287
     * 数字、下划线
288
     * @param $prefix     同一个 bucket 里面前缀不能重复
289
     * @param $delete_after_days      指定上传文件多少天后删除,指定为0表示不删除,
290
     * 大于0表示多少天后删除,需大于 to_line_after_days
291
     * @param $to_line_after_days  指定文件上传多少天后转低频存储。指定为0表示不
292
     * 转低频存储,小于0表示上传的文件立即变低频存储
293
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
294
     */
295
    public function updateBucketLifecycleRule(
296
        $bucket,
297
        $name,
298
        $prefix,
299
        $delete_after_days,
300
        $to_line_after_days
301
    ) {
302
        $path = '/rules/update';
303
        if ($bucket) {
304
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
305
        }
306
        if ($name) {
307
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
308
        }
309
        if ($prefix) {
310
            $params['prefix'] = $prefix;
311
        }
312
        if ($delete_after_days) {
313
            $params['delete_after_days'] = $delete_after_days;
314
        }
315
        if ($to_line_after_days) {
316
            $params['to_line_after_days'] = $to_line_after_days;
317
        }
318
        $data = http_build_query($params);
319
        $info = $this->ucPost($path, $data);
320
        return $info;
321
    }
322
323
    /**
324
     * 获取bucket生命规则
325
     *
326
     * @param $bucket     空间名
327
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
328
     */
329
    public function getBucketLifecycleRules($bucket)
330
    {
331
        $path = '/rules/get?bucket=' . $bucket;
332
        $info = $this->ucGet($path);
333
        return $info;
334
    }
335
336
    /**
337
     * 删除bucket生命规则
338
     *
339
     * @param $bucket     空间名
340
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
341
     * 只能为字母、数字、下划线()
342
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
343
     */
344
    public function deleteBucketLifecycleRule($bucket, $name)
345
    {
346
        $path = '/rules/delete';
347
        if ($bucket) {
348
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
349
        }
350
        if ($name) {
351
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
352
        }
353
        $data = http_build_query($params);
354
        $info = $this->ucPost($path, $data);
355
        return $info;
356
    }
357
358
    /**
359
     * 增加bucket事件通知规则
360
     *
361
     * @param $bucket     空间名
362
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
363
     * 只能为字母、数字、下划线()
364
     * @param $prefix     同一个 bucket 里面前缀不能重复
365
     * @param $suffix      可选,文件配置的后缀
366
     * @param $event  事件类型,可以指定多个,包括 put,mkfile,delete,copy,move,append,
367
     * disable,enable,deleteMarkerCreate
368
     * @param $callbackURL 通知URL,可以指定多个,失败依次重试
369
     * @param $access_key 可选,设置的话会对通知请求用对应的ak、sk进行签名
370
     * @param $host 可选,通知请求的host
371
     *
372
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
373
     */
374
    public function putBucketEvent(
375
        $bucket,
376
        $name,
377
        $prefix,
378
        $suffix,
379
        $event,
380
        $callbackURL,
381
        $access_key = null,
382
        $host = null
383
    ) {
384
        $path = '/events/add';
385
        if ($bucket) {
386
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
387
        }
388
        if ($name) {
389
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
390
        }
391
        if ($prefix) {
392
            $params['prefix'] = $prefix;
393
        }
394
        if ($suffix) {
395
            $params['suffix'] = $suffix;
396
        }
397
        if ($callbackURL) {
398
            $params['callbackURL'] = $callbackURL;
399
        }
400
        if ($access_key) {
401
            $params['access_key'] = $access_key;
402
        }
403
        if ($host) {
404
            $params['host'] = $host;
405
        }
406
        $data = http_build_query($params);
407
        if ($event) {
408
            $eventpath = "";
409
            foreach ($event as $key => $value) {
410
                $eventpath .= "&event=$value";
411
            }
412
            $data .= $eventpath;
413
        }
414
        $info = $this->ucPost($path, $data);
415
        return $info;
416
    }
417
418
    /**
419
     * 更新bucket事件通知规则
420
     *
421
     * @param $bucket     空间名
422
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
423
     * 只能为字母、数字、下划线()
424
     * @param $prefix     同一个 bucket 里面前缀不能重复
425
     * @param $suffix      可选,文件配置的后缀
426
     * @param $event  事件类型,可以指定多个,包括 put,mkfile,delete,copy,move,append,disable,
427
     * enable,deleteMarkerCreate
428
     * @param $callbackURL 通知URL,可以指定多个,失败依次重试
429
     * @param $access_key 可选,设置的话会对通知请求用对应的ak、sk进行签名
430
     * @param $host 可选,通知请求的host
431
     *
432
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
433
     */
434
    public function updateBucketEvent(
435
        $bucket,
436
        $name,
437
        $prefix,
438
        $suffix,
439
        $event,
440
        $callbackURL,
441
        $access_key = null,
442
        $host = null
443
    ) {
444
        $path = '/events/update';
445
        if ($bucket) {
446
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
447
        }
448
        if ($name) {
449
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
450
        }
451
        if ($prefix) {
452
            $params['prefix'] = $prefix;
453
        }
454
        if ($suffix) {
455
            $params['suffix'] = $suffix;
456
        }
457
        if ($event) {
458
            $params['event'] = $event;
459
        }
460
        if ($callbackURL) {
461
            $params['callbackURL'] = $callbackURL;
462
        }
463
        if ($access_key) {
464
            $params['access_key'] = $access_key;
465
        }
466
        if ($host) {
467
            $params['host'] = $host;
468
        }
469
        $data = http_build_query($params);
470
        $info = $this->ucPost($path, $data);
471
        return $info;
472
    }
473
474
    /**
475
     * 获取bucket事件通知规则
476
     *
477
     * @param $bucket     空间名
478
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
479
     */
480
    public function getBucketEvents($bucket)
481
    {
482
        $path = '/events/get?bucket=' . $bucket;
483
        $info = $this->ucGet($path);
484
        return $info;
485
    }
486
487
    /**
488
     * 删除bucket事件通知规则
489
     *
490
     * @param $bucket     空间名
491
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
492
     * 只能为字母、数字、下划线
493
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
494
     */
495
    public function deleteBucketEvent($bucket, $name)
496
    {
497
        $path = '/events/delete';
498
        if ($bucket) {
499
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
500
        }
501
        if ($name) {
502
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
503
        }
504
        $data = http_build_query($params);
505
        $info = $this->ucPost($path, $data);
506
        return $info;
507
    }
508
509
    /**
510
     * 设置bucket的跨域信息,最多允许设置10条跨域规则。
511
     * 对于同一个域名如果设置了多条规则,那么按顺序使用第一条匹配的规则去生成返回值。
512
     * 对于简单跨域请求,只匹配 Origin;
513
     * allowed_orgin: 允许的域名。必填;支持通配符*;*表示全部匹配;只有第一个*生效;
514
     * 需要设置"Scheme";大小写敏感。例如
515
     * 规则:http://*.abc.*.com 请求:"http://test.abc.test.com" 结果:不通过
516
     * 规则:"http://abc.com" 请求:"https://abc.com"/"abc.com" 结果:不通过
517
     * 规则:"abc.com" 请求:"http://abc.com" 结果:不通过
518
     * allowed_method: 允许的方法。必填;不支持通配符;大小写不敏感;
519
     * allowed_header: 允许的header。选填;支持通配符*,
520
     * 但只能是单独的*,表示允许全部header,其他*不生效;
521
     * 空则不允许任何header;大小写不敏感;
522
     * exposed_header: 暴露的header。选填;不支持通配符;
523
     * X-Log, X-Reqid是默认会暴露的两个header;
524
     * 其他的header如果没有设置,则不会暴露;大小写不敏感;
525
     * max_age: 结果可以缓存的时间。选填;空则不缓存;
526
     * allowed_credentials:该配置不支持设置,默认为true。
527
     * 备注:如果没有设置任何corsRules,那么默认允许所有的跨域请求
528
     */
529
    // public function putCorsRules(string $bucket, array $params)
530
    // {
531
    //     $path = '/corsRules/set/' . $bucket;
532
    //     $data = json_encode($params);
533
    //     $info = $this->ucPost($path, $data);
534
    //     return $info;
535
    // }
536
537
    /**
538
     * 获取bucket的跨域信息
539
     * $bucket 空间名
540
     */
541
    public function getCorsRules($bucket)
542
    {
543
        $path = '/corsRules/get/' . $bucket;
544
        $info = $this->ucGet($path);
545
        return $info;
546
    }
547
548
    /**
549
     * 设置回源规则
550
     * 使用该API设置源站优先级高于/image设置的源站,即IO优先读取source接口设置的源站配置,
551
     * 如果存在会忽略/image设置的源站
552
     * Bucket 空间名
553
     * Host(可选)回源Host
554
     * RetryCodes(可选),镜像回源时源站返回Code可以重试,最多指定3个,当前只支持4xx错误码重试
555
     * SourceQiniuAK,SourceQiniuSK(可选)如果存在将在回源时对URL进行签名,客户源站可以验证
556
     * 以保证请求来自Qiniu服务器
557
     * Expires(可选) 签名过期时间,如果不设置默认为1小时
558
     * Addr 回源地址,不可重复。
559
     * Weight 权重,范围限制1-100,不填默认为1,回源时会根据所有源的权重值进行源站选择,
560
     * 主备源会分开计算.
561
     * Backup 是否备用回源,回源优先尝试主源
562
     */
563
    // public function putBucktSourceConfig(array $params)
564
    // {
565
    //     $path = '/mirrorConfig/set';
566
    //     $data = json_encode($params);
567
    //     $info = $this->ucPostV2($path, $data);
568
    //     return $info;
569
    // }
570
571
    /**
572
     * 获取空间回源配置
573
     */
574
    public function getBucktSourceConfig(array $params)
575
    {
576
        $path = '/mirrorConfig/get';
577
        $data = json_encode($params);
578
        $info = $this->ucPostV2($path, $data);
579
        return $info;
580
    }
581
582
    /**
583
     * 开关原图保护
584
     * mode 为1表示开启原图保护,0表示关闭
585
     */
586
    public function putBucketAccessStyleMode($bucket, $mode)
587
    {
588
        $path = '/accessMode/' . $bucket . '/mode/' . $mode;
589
        $info = $this->ucPost($path, null);
590
        return $info;
591
    }
592
593
    /**
594
     * 设置私有属性
595
     * private为0表示公开,为1表示私有
596
     */
597
    public function putBucketAccessMode($bucket, $private)
598
    {
599
        $path = '/bucket/' . $bucket . '/private/' . $private;
600
        $info = $this->ucPost($path, null);
601
        return $info;
602
    }
603
604
    /**
605
     * 设置referer防盗链
606
     * bucket=<BucketName>: bucket 名
607
     * mode=<AntiLeechMode>:
608
     * 0: 表示关闭Referer(使用此选项将会忽略以下参数并将恢复默认值);
609
     * 1: 表示设置Referer白名单; 2: 表示设置Referer黑名单
610
     * norefer=<NoRefer>: 0: 表示不允许空 Refer 访问;
611
     * 1: 表示允许空 Refer 访问
612
     * pattern=<Pattern>: 规则字符串, 当前允许格式分为三种:
613
     * 一种为空主机头域名, 比如 foo.com;
614
     * 一种是泛域名, 比如 *.bar.com; 一种是完全通配符, 即一个 *;
615
     * 多个规则之间用;隔开, 比如: foo.com;*.bar.com;sub.foo.com;*.sub.bar.com
616
     * 空主机头域名可以是多级域名,比如 foo.bar.com。
617
     * 多个域名之间不允许夹带空白字符。
618
     * source_enabled=:1
619
     */
620
    public function putReferAntiLeech($bucket, $mode, $norefer, $pattern, $enabled = 1)
621
    {
622
        $path = "/referAntiLeech?bucket=$bucket&mode=$mode&norefer=$norefer&pattern=$pattern&source_enabled=$enabled";
623
        $info = $this->ucPost($path, null);
624
        return $info;
625
    }
626
627
    /**
628
     * 设置Bucket的maxAge
629
     * maxAge为0或者负数表示为默认值(31536000)
630
     */
631
    public function putBucketMaxAge($bucket, $maxAge)
632
    {
633
        $path = '/maxAge?bucket=' . $bucket . '&maxAge=' . $maxAge;
634
        $info = $this->ucPost($path, null);
635
        return $info;
636
    }
637
638
    /**
639
     * 设置配额
640
     * <bucket>: 空间名称,不支持授权空间
641
     * <size>: 空间存储量配额,参数传入0或不传表示不更改当前配置,传入-1表示取消限额,
642
     * 新创建的空间默认没有限额。
643
     * <count>: 空间文件数配额,参数含义同<size>
644
     */
645
    public function putBucketQuota($bucket, $size, $count)
646
    {
647
        $path = '/setbucketquota/' . $bucket . '/size/' . $size . '/count/' . $count;
648
        $info = $this->apiPost($path, null);
649
        return $info;
650
    }
651
652
    /**
653
     * 获取配额
654
     * bucket 空间名称
655
     */
656
    public function getBucketQuota($bucket)
657
    {
658
        $path = '/getbucketquota/' . $bucket;
659
        $info = $this->apiPost($path, null);
660
        return $info;
661
    }
662
663
    /**
664
     * 获取资源的元信息,但不返回文件内容
665
     *
666
     * @param $bucket     待获取信息资源所在的空间
667
     * @param $key        待获取资源的文件名
668
     *
669
     * @return array    包含文件信息的数组,类似:
670
*                                              [
671
*                                                  "hash" => "<Hash string>",
672
*                                                  "key" => "<Key string>",
673
*                                                  "fsize" => <file size>,
674
*                                                  "putTime" => "<file modify time>"
675
*                                                  "fileType" => <file type>
676
*                                              ]
677 6
     *
678
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
679 6
     */
680 6
    public function stat($bucket, $key)
681
    {
682
        $path = '/stat/' . \Qiniu\entry($bucket, $key);
683
        return $this->rsGet($path);
684
    }
685
686
    /**
687
     * 删除指定资源
688
     *
689
     * @param $bucket     待删除资源所在的空间
690
     * @param $key        待删除资源的文件名
691
     *
692 15
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
693
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
694 15
     */
695 15
    public function delete($bucket, $key)
696 15
    {
697
        $path = '/delete/' . \Qiniu\entry($bucket, $key);
698
        list(, $error) = $this->rsPost($path);
699
        return $error;
700
    }
701
702
703
    /**
704
     * 给资源进行重命名,本质为move操作。
705
     *
706
     * @param $bucket     待操作资源所在空间
707
     * @param $oldname    待操作资源文件名
708
     * @param $newname    目标资源文件名
709 3
     *
710
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
711 3
     */
712
    public function rename($bucket, $oldname, $newname)
713
    {
714
        return $this->move($bucket, $oldname, $bucket, $newname);
715
    }
716
717
    /**
718
     * 对资源进行复制。
719
     *
720
     * @param $from_bucket     待操作资源所在空间
721
     * @param $from_key        待操作资源文件名
722
     * @param $to_bucket       目标资源空间名
723
     * @param $to_key          目标资源文件名
724
     *
725 15
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
726
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/copy.html
727 15
     */
728 15
    public function copy($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
729 15
    {
730 15
        $from = \Qiniu\entry($from_bucket, $from_key);
731 3
        $to = \Qiniu\entry($to_bucket, $to_key);
732 3
        $path = '/copy/' . $from . '/' . $to;
733 15
        if ($force === true) {
734 15
            $path .= '/force/true';
735
        }
736
        list(, $error) = $this->rsPost($path);
737
        return $error;
738
    }
739
740
    /**
741
     * 将资源从一个空间到另一个空间
742
     *
743
     * @param $from_bucket     待操作资源所在空间
744
     * @param $from_key        待操作资源文件名
745
     * @param $to_bucket       目标资源空间名
746
     * @param $to_key          目标资源文件名
747
     *
748 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
749
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
750 3
     */
751 3
    public function move($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
752 3
    {
753 3
        $from = \Qiniu\entry($from_bucket, $from_key);
754
        $to = \Qiniu\entry($to_bucket, $to_key);
755
        $path = '/move/' . $from . '/' . $to;
756 3
        if ($force) {
757 3
            $path .= '/force/true';
758
        }
759
        list(, $error) = $this->rsPost($path);
760
        return $error;
761
    }
762
763
    /**
764
     * 主动修改指定资源的文件元信息
765
     *
766
     * @param $bucket     待操作资源所在空间
767
     * @param $key        待操作资源文件名
768
     * @param $mime       待操作文件目标mimeType
769
     *
770 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
771
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
772 3
     */
773 3
    public function changeMime($bucket, $key, $mime)
774 3
    {
775 3
        $resource = \Qiniu\entry($bucket, $key);
776 3
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
777
        $path = '/chgm/' . $resource . '/mime/' . $encode_mime;
778
        list(, $error) = $this->rsPost($path);
779
        return $error;
780
    }
781
782
783
    /**
784
     * 修改指定资源的存储类型
785
     *
786
     * @param $bucket     待操作资源所在空间
787
     * @param $key        待操作资源文件名
788
     * @param $fileType       待操作文件目标文件类型
789
     *
790
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
791
     * @link  https://developer.qiniu.com/kodo/api/3710/modify-the-file-type
792
     */
793
    public function changeType($bucket, $key, $fileType)
794
    {
795
        $resource = \Qiniu\entry($bucket, $key);
796
        $path = '/chtype/' . $resource . '/type/' . $fileType;
797
        list(, $error) = $this->rsPost($path);
798
        return $error;
799
    }
800
801
    /**
802
     * 修改指定资源的存储类型
803
     *
804
     * @param $bucket     待操作资源所在空间
805
     * @param $key        待操作资源文件名
806
     * @param $day        解冻有效时长,取值范围 1~7
807
     *
808
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
809
     * @link  https://developer.qiniu.com/kodo/api/6380/restore-archive
810
     */
811
    public function restoreFile($bucket, $key, $day)
812
    {
813
        $resource = \Qiniu\entry($bucket, $key);
814
        $path = '/restoreAr/' . $resource . '/freezeAfterDays/' . $day;
815
        list(, $error) = $this->rsPost($path);
816
        return $error;
817
    }
818
819
    /**
820
     * 修改文件的存储状态,即禁用状态和启用状态间的的互相转换
821
     *
822
     * @param $bucket     待操作资源所在空间
823
     * @param $key        待操作资源文件名
824
     * @param $status       待操作文件目标文件类型
825
     *
826
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
827
     * @link  https://developer.qiniu.com/kodo/api/4173/modify-the-file-status
828
     */
829
    public function changeStatus($bucket, $key, $status)
830
    {
831
        $resource = \Qiniu\entry($bucket, $key);
832
        $path = '/chstatus/' . $resource . '/status/' . $status;
833
        list(, $error) = $this->rsPost($path);
834
        return $error;
835
    }
836
837
    /**
838 3
     * 从指定URL抓取资源,并将该资源存储到指定空间中
839
     *
840
     * @param $url        指定的URL
841 3
     * @param $bucket     目标资源空间
842 3
     * @param $key        目标资源文件名
843 3
     *
844
     * @return array    包含已拉取的文件信息。
845 3
     *                         成功时:  [
846 3
     *                                          [
847
     *                                              "hash" => "<Hash string>",
848 3
     *                                              "key" => "<Key string>"
849 3
     *                                          ],
850
     *                                          null
851
     *                                  ]
852
     *
853
     *                         失败时:  [
854
     *                                          null,
855
     *                                         Qiniu/Http/Error
856
     *                                  ]
857
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
858
     */
859
    public function fetch($url, $bucket, $key = null)
860
    {
861 3
862
        $resource = \Qiniu\base64_urlSafeEncode($url);
863 3
        $to = \Qiniu\entry($bucket, $key);
864 3
        $path = '/fetch/' . $resource . '/to/' . $to;
865
866 3
        $ak = $this->auth->getAccessKey();
867 3
        $ioHost = $this->config->getIovipHost($ak, $bucket);
868
869 3
        $url = $ioHost . $path;
870 3
        return $this->post($url, null);
871 3
    }
872
873
    /**
874
     * 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源
875
     *
876
     * @param $bucket     待获取资源所在的空间
877
     * @param $key        代获取资源文件名
878
     *
879
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
880
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
881
     */
882
    public function prefetch($bucket, $key)
883
    {
884
        $resource = \Qiniu\entry($bucket, $key);
885
        $path = '/prefetch/' . $resource;
886
887
        $ak = $this->auth->getAccessKey();
888
        $ioHost = $this->config->getIovipHost($ak, $bucket);
889
890 12
        $url = $ioHost . $path;
891
        list(, $error) = $this->post($url, null);
892 12
        return $error;
893 12
    }
894
895
    /**
896
     * 在单次请求中进行多个资源管理操作
897
     *
898
     * @param $operations     资源管理操作数组
899
     *
900
     * @return array 每个资源的处理情况,结果类似:
901
     *              [
902
     *                   { "code" => <HttpCode int>, "data" => <Data> },
903
     *                   { "code" => <HttpCode int> },
904
     *                   { "code" => <HttpCode int> },
905
     *                   { "code" => <HttpCode int> },
906 3
     *                   { "code" => <HttpCode int>, "data" => { "error": "<ErrorMessage string>" } },
907
     *                   ...
908 3
     *               ]
909 3
     * @link http://developer.qiniu.com/docs/v6/api/reference/rs/batch.html
910 3
     */
911 3
    public function batch($operations)
912
    {
913
        $params = 'op=' . implode('&op=', $operations);
914 3
        return $this->rsPost('/batch', $params);
915
    }
916 3
917 3
    /**
918
     * 设置文件的生命周期
919
     *
920 3
     * @param $bucket 设置文件生命周期文件所在的空间
921
     * @param $key    设置文件生命周期文件的文件名
922
     * @param $days   设置该文件多少天后删除,当$days设置为0时表示取消该文件的生命周期
923 33
     *
924
     * @return Mixed
925 33
     * @link https://developer.qiniu.com/kodo/api/update-file-lifecycle
926 33
     */
927
    public function deleteAfterDays($bucket, $key, $days)
928
    {
929 33
        $entry = \Qiniu\entry($bucket, $key);
930
        $path = "/deleteAfterDays/$entry/$days";
931
        list(, $error) = $this->rsPost($path);
932
        return $error;
933
    }
934
935
    private function getRsfHost()
936
    {
937
        $scheme = "http://";
938
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
939
            $scheme = "https://";
940
        }
941
        return $scheme . Config::RSF_HOST;
942
    }
943
944
    private function getRsHost()
945
    {
946
        $scheme = "http://";
947
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
948
            $scheme = "https://";
949
        }
950 27
        return $scheme . Config::RS_HOST;
951
    }
952 27
953 27
    private function getApiHost()
954
    {
955
        $scheme = "http://";
956
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
957
            $scheme = "https://";
958
        }
959
        return $scheme . Config::API_HOST;
960
    }
961
962
    private function getUcHost()
963
    {
964
        $scheme = "http://";
965
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
966
            $scheme = "https://";
967
        }
968
        return $scheme . Config::UC_HOST;
969
    }
970
971
    private function rsPost($path, $body = null)
972
    {
973
        $url = $this->getRsHost() . $path;
974
        return $this->post($url, $body);
975
    }
976
977
    private function apiPost($path, $body = null)
978
    {
979
        $url = $this->getApiHost() . $path;
980 9
        return $this->post($url, $body);
981
    }
982 9
983 9
    private function ucPost($path, $body = null)
984
    {
985
        $url = $this->getUcHost() . $path;
986 12
        return $this->post($url, $body);
987
    }
988 12
989 12
    private function ucGet($path)
990 12
    {
991 6
        $url = $this->getUcHost() . $path;
992
        return $this->get($url);
993 12
    }
994
995
    private function apiGet($path)
996 33
    {
997
        $url = $this->getApiHost() . $path;
998 33
        return $this->get($url);
999 33
    }
1000 33
1001 9
    private function rsGet($path)
1002
    {
1003 30
        $url = $this->getRsHost() . $path;
1004 30
        return $this->get($url);
1005
    }
1006
1007
    private function get($url)
1008
    {
1009
        $headers = $this->auth->authorization($url);
1010
        $ret = Client::get($url, $headers);
1011
        if (!$ret->ok()) {
1012
            return array(null, new Error($url, $ret));
1013
        }
1014
        return array($ret->json(), null);
1015
    }
1016
1017
    private function post($url, $body)
1018
    {
1019
        $headers = $this->auth->authorization($url, $body, 'application/x-www-form-urlencoded');
1020
        $ret = Client::post($url, $body, $headers);
1021
        if (!$ret->ok()) {
1022
            return array(null, new Error($url, $ret));
1023
        }
1024
        $r = ($ret->body === null) ? array() : $ret->json();
1025 3
        return array($r, null);
1026
    }
1027 3
1028
    private function ucPostV2($path, $body)
1029
    {
1030
        $url = $this->getUcHost() . $path;
1031 3
        return $this->postV2($url, $body);
1032
    }
1033 3
1034
    private function postV2($url, $body)
1035
    {
1036
        $headers = $this->auth->authorizationV2($url, 'POST', $body, 'application/json');
1037 6
        $headers["Content-Type"] = 'application/json';
1038
        $ret = Client::post($url, $body, $headers);
1039 6
        if (!$ret->ok()) {
1040
            return array(null, new Error($url, $ret));
1041
        }
1042
        $r = ($ret->body === null) ? array() : $ret->json();
1043 3
        return array($r, null);
1044
    }
1045 3
1046
    public static function buildBatchCopy($source_bucket, $key_pairs, $target_bucket, $force)
1047
    {
1048
        return self::twoKeyBatch('/copy', $source_bucket, $key_pairs, $target_bucket, $force);
1049 3
    }
1050
1051 3
1052
    public static function buildBatchRename($bucket, $key_pairs, $force)
1053
    {
1054
        return self::buildBatchMove($bucket, $key_pairs, $bucket, $force);
1055
    }
1056
1057
1058
    public static function buildBatchMove($source_bucket, $key_pairs, $target_bucket, $force)
1059
    {
1060
        return self::twoKeyBatch('/move', $source_bucket, $key_pairs, $target_bucket, $force);
1061
    }
1062
1063
1064
    public static function buildBatchDelete($bucket, $keys)
1065
    {
1066
        return self::oneKeyBatch('/delete', $bucket, $keys);
1067
    }
1068
1069
1070
    public static function buildBatchStat($bucket, $keys)
1071
    {
1072
        return self::oneKeyBatch('/stat', $bucket, $keys);
1073
    }
1074
1075
    public static function buildBatchDeleteAfterDays($bucket, $key_day_pairs)
1076
    {
1077
        $data = array();
1078
        foreach ($key_day_pairs as $key => $day) {
1079
            array_push($data, '/deleteAfterDays/' . \Qiniu\entry($bucket, $key) . '/' . $day);
1080
        }
1081 6
        return $data;
1082
    }
1083 6
1084 6
    public static function buildBatchChangeMime($bucket, $key_mime_pairs)
1085 6
    {
1086 6
        $data = array();
1087 6
        foreach ($key_mime_pairs as $key => $mime) {
1088
            array_push($data, '/chgm/' . \Qiniu\entry($bucket, $key) . '/mime/' . base64_encode($mime));
1089
        }
1090 9
        return $data;
1091
    }
1092 9
1093
    public static function buildBatchChangeType($bucket, $key_type_pairs)
1094
    {
1095 9
        $data = array();
1096 9
        foreach ($key_type_pairs as $key => $type) {
1097 9
            array_push($data, '/chtype/' . \Qiniu\entry($bucket, $key) . '/type/' . $type);
1098 9
        }
1099 9
        return $data;
1100 9
    }
1101 9
1102 9
    private static function oneKeyBatch($operation, $bucket, $keys)
1103 9
    {
1104 9
        $data = array();
1105 9
        foreach ($keys as $key) {
1106
            array_push($data, $operation . '/' . \Qiniu\entry($bucket, $key));
1107
        }
1108
        return $data;
1109
    }
1110
1111
    private static function twoKeyBatch($operation, $source_bucket, $key_pairs, $target_bucket, $force)
1112
    {
1113
        if ($target_bucket === null) {
1114
            $target_bucket = $source_bucket;
1115
        }
1116
        $data = array();
1117
        $forceOp = "false";
1118
        if ($force) {
1119
            $forceOp = "true";
1120
        }
1121
        foreach ($key_pairs as $from_key => $to_key) {
1122
            $from = \Qiniu\entry($source_bucket, $from_key);
1123
            $to = \Qiniu\entry($target_bucket, $to_key);
1124
            array_push($data, $operation . '/' . $from . '/' . $to . "/force/" . $forceOp);
1125
        }
1126
        return $data;
1127
    }
1128
}
1129