Completed
Pull Request — master (#293)
by
unknown
08:26
created

BucketManager::putBucketEvent()   C

Complexity

Conditions 10
Paths 256

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 10.1953

Importance

Changes 0
Metric Value
cc 10
nc 256
nop 8
dl 0
loc 43
ccs 21
cts 24
cp 0.875
crap 10.1953
rs 6.1333
c 0
b 0
f 0

How to fix   Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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'
0 ignored issues
show
Unused Code introduced by
The parameter $shared is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
61
    ) {
62
        $path = '/v3/buckets?region=' . $region . '&line=' . $line . '&shared=' . $share;
0 ignored issues
show
Bug introduced by
The variable $share does not exist. Did you mean $shared?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
63
        $info = $this->ucPost($path);
64
        return $info;
65
    }
66
67
    /**
68
     * 创建空间
69
     *
70
     * @param $name     创建的空间名
71
     * @param $region    创建的区域,默认华东
72
     *
73
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
74
     */
75
    public function createBucket($name, $region = 'z0')
76
    {
77
        $path = '/mkbucketv2/'.$name.'/region/' . $region;
78
        return $this->rsPost($path, null);
79 3
    }
80
81 3
    /**
82 3
     * 删除空间
83 3
     *
84 3
     * @param $name     删除的空间名
85 3
     *
86 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
87 3
     */
88
    public function deleteBucket($name)
89
    {
90
        $path = '/drop/'.$name;
91
        return $this->rsPost($path, null);
92
    }
93
94
    /**
95
     * 获取指定空间绑定的所有的域名
96
     *
97
     * @return string[] 包含所有空间域名
98
     */
99
    public function domains($bucket)
100
    {
101
        return $this->apiGet('/v6/domain/list?tbl=' . $bucket);
102
    }
103
104
    /**
105
     * 获取指定空间的相关信息
106
     *
107 6
     * @return string[] 包含空间信息
108
     */
109 6
    public function bucketInfo($bucket)
110 6
    {
111
        $path = '/v2/bucketInfo?bucket=' . $bucket;
112
        $info = $this->ucPost($path);
113
        return $info;
114
    }
115
116
    /**
117
     * 获取指定zone的空间信息列表
118
     * 在Region 未指定且Global 不为 true 时(包含未指定的情况,下同),返回用户的所有空间。
119
     * 在指定了 region 参数且 global 不为 true 时,只列举非全局空间。
120
     * shared 不指定shared参数或指定shared为rw或false时,返回包含具有读写权限空间,
121
     * 指定shared为rd或true时,返回包含具有读权限空间。
122 15
     * fs:如果为 true,会返回每个空间当前的文件数和存储量(实时数据)。
123
     * @return string[] 包含空间信息
124 15
     */
125 15
    public function bucketInfos($region = null, $shared = 'false', $fs = 'false')
126 15
    {
127
        $path = '/v2/bucketInfos?region=' . $region . '&shared=' . $shared . '&fs=' . $fs;
128
        $info = $this->ucPost($path);
129
        return $info;
130
    }
131
132
    /**
133
     * 获取空间绑定的域名列表
134
     * @return string[] 包含空间绑定的所有域名
135
     */
136
137
    /**
138
     * 列取空间的文件列表
139 3
     *
140
     * @param $bucket     空间名
141 3
     * @param $prefix     列举前缀
142
     * @param $marker     列举标识符
143
     * @param $limit      单次列举个数限制
144
     * @param $delimiter  指定目录分隔符
145
     *
146
     * @return array    包含文件信息的数组,类似:[
147
*                                              {
148
*                                                 "hash" => "<Hash string>",
149
*                                                  "key" => "<Key string>",
150
*                                                  "fsize" => "<file size>",
151
*                                                  "putTime" => "<file modify time>"
152
*                                              },
153
*                                              ...
154
*                                            ]
155 15
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
156
     */
157 15
    public function listFiles(
158 15
        $bucket,
159 15
        $prefix = null,
160 15
        $marker = null,
161 3
        $limit = 1000,
162 3
        $delimiter = null
163 15
    ) {
164 15
        $query = array('bucket' => $bucket);
165
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
166
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
167
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
168
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
169
        $url = $this->getRsfHost() . '/list?' . http_build_query($query);
170
        return $this->get($url);
171
    }
172
173
    /**
174
     * 列取空间的文件列表
175
     *
176
     * @param $bucket     空间名
177
     * @param $prefix     列举前缀
178 3
     * @param $marker     列举标识符
179
     * @param $limit      单次列举个数限制
180 3
     * @param $delimiter  指定目录分隔符
181 3
     * @param $skipconfirm  是否跳过已删除条目的确认机制
182 3
     *
183 3
     * @return array    包含文件信息的数组,类似:[
184
*                                              {
185
*                                                 "hash" => "<Hash string>",
186 3
*                                                  "key" => "<Key string>",
187 3
*                                                  "fsize" => "<file size>",
188
*                                                  "putTime" => "<file modify time>"
189
*                                              },
190
*                                              ...
191
*                                            ]
192
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
193
     */
194
    public function listFilesv2(
195
        $bucket,
196
        $prefix = null,
197
        $marker = null,
198
        $limit = 1000,
199
        $delimiter = null,
200 3
        $skipconfirm = true
201
    ) {
202 3
        $query = array('bucket' => $bucket);
203 3
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
204 3
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
205 3
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
206 3
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
207
        \Qiniu\setWithoutEmpty($query, 'skipconfirm', $skipconfirm);
208
        $path = '/v2/list?' . http_build_query($query);
209
        $url = $this->getRsfHost() . $path;
210
        $headers = $this->auth->authorization($url, null, 'application/x-www-form-urlencoded');
211
        $ret = Client::post($url, null, $headers);
212
        if (!$ret->ok()) {
213
            return array(null, new Error($url, $ret));
214
        }
215
        $r = explode("\n", $ret->body);
216
        $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...
217
        return array($r, null);
218
    }
219
220
    /**
221
     * 设置Referer防盗链
222
     *
223
     * @param $bucket     空间名
224
     * @param $mode     0: 表示关闭Referer(使用此选项将会忽略以下参数并将恢复默认值);
225
     * 1: 表示设置Referer白名单; 2:表示设置Referer黑名单
226
     * @param $norefer     0: 表示不允许空 Refer 访问; 1: 表示允许空 Refer 访问
227
     * @param $pattern      规则字符串, 当前允许格式分为三种: 一种为空主机头域名,
228
     * 比如 foo.com; 一种是泛域名,比如 *.bar.com; 一种是完全通配符,
229
     * 即一个 *; 多个规则之间用;隔开, 比如: foo.com;*.bar.com;sub.foo.com;*.sub.bar.com
230
     * @param $source_enabled  源站是否支持,默认为0只给CDN配置, 设置为1表示开启源站防盗链
231
     *
232
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
233
     */
234
    // public function referAntiLeech(){
235
236
    // }
237
238
    /**
239
     * 增加bucket生命规则
240
     *
241
     * @param $bucket     空间名
242
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,只能为
243
     * 字母、数字、下划线
244
     * @param $prefix     同一个 bucket 里面前缀不能重复
245
     * @param $delete_after_days      指定上传文件多少天后删除,指定为0表示不删除,
246
     * 大于0表示多少天后删除,需大于 to_line_after_days
247
     * @param $to_line_after_days  指定文件上传多少天后转低频存储。指定为0表示
248
     * 不转低频存储,小于0表示上传的文件立即变低频存储
249
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
250
     */
251
    public function bucketLifecycleRule(
252
        $bucket,
253
        $name,
254
        $prefix,
255
        $delete_after_days,
256
        $to_line_after_days
257
    ) {
258
        $path = '/rules/add';
259
        if ($bucket) {
260
            $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...
261
        }
262
        if ($name) {
263
            $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...
264
        }
265
        if ($prefix) {
266
            $params['prefix'] = $prefix;
267
        }
268 3
        if ($delete_after_days) {
269
            $params['delete_after_days'] = $delete_after_days;
270
        }
271 3
        if ($to_line_after_days) {
272 3
            $params['to_line_after_days'] = $to_line_after_days;
273 3
        }
274
        $data = http_build_query($params);
275 3
        $info = $this->ucPost($path, $data);
276 3
        return $info;
277
    }
278 3
279 3
    /**
280
     * 更新bucket生命规则
281
     *
282
     * @param $bucket     空间名
283
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,只能为字母、
284
     * 数字、下划线
285
     * @param $prefix     同一个 bucket 里面前缀不能重复
286
     * @param $delete_after_days      指定上传文件多少天后删除,指定为0表示不删除,
287
     * 大于0表示多少天后删除,需大于 to_line_after_days
288
     * @param $to_line_after_days  指定文件上传多少天后转低频存储。指定为0表示不
289
     * 转低频存储,小于0表示上传的文件立即变低频存储
290
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
291 3
     */
292
    public function updateBucketLifecycleRule(
293 3
        $bucket,
294 3
        $name,
295
        $prefix,
296 3
        $delete_after_days,
297 3
        $to_line_after_days
298
    ) {
299 3
        $path = '/rules/update';
300 3
        if ($bucket) {
301 3
            $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...
302
        }
303
        if ($name) {
304
            $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...
305
        }
306
        if ($prefix) {
307
            $params['prefix'] = $prefix;
308
        }
309
        if ($delete_after_days) {
310
            $params['delete_after_days'] = $delete_after_days;
311
        }
312
        if ($to_line_after_days) {
313
            $params['to_line_after_days'] = $to_line_after_days;
314
        }
315
        $data = http_build_query($params);
316
        $info = $this->ucPost($path, $data);
317
        return $info;
318
    }
319
320 12
    /**
321
     * 获取bucket生命规则
322 12
     *
323 12
     * @param $bucket     空间名
324
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
325
     */
326
    public function getBucketLifecycleRules($bucket)
327
    {
328
        $path = '/rules/get?bucket=' . $bucket;
329
        $info = $this->ucGet($path);
330
        return $info;
331
    }
332
333
    /**
334
     * 删除bucket生命规则
335
     *
336 3
     * @param $bucket     空间名
337
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
338 3
     * 只能为字母、数字、下划线()
339 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
340 3
     */
341 3
    public function deleteBucketLifecycleRule($bucket, $name)
342
    {
343
        $path = '/rules/delete';
344 3
        if ($bucket) {
345
            $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...
346 3
        }
347 3
        if ($name) {
348
            $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...
349
        }
350 3
        $data = http_build_query($params);
351
        $info = $this->ucPost($path, $data);
352
        return $info;
353 33
    }
354
355 33
    /**
356 33
     * 增加bucket事件通知规则
357
     *
358
     * @param $bucket     空间名
359 33
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
360
     * 只能为字母、数字、下划线()
361
     * @param $prefix     同一个 bucket 里面前缀不能重复
362
     * @param $suffix      可选,文件配置的后缀
363
     * @param $event  事件类型,可以指定多个,包括 put,mkfile,delete,copy,move,append,
364
     * disable,enable,deleteMarkerCreate
365
     * @param $callbackURL 通知URL,可以指定多个,失败依次重试
366
     * @param $access_key 可选,设置的话会对通知请求用对应的ak、sk进行签名
367
     * @param $host 可选,通知请求的host
368
     *
369
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
370
     */
371 27
    public function putBucketEvent(
372
        $bucket,
373 27
        $name,
374 27
        $prefix,
375
        $suffix,
376
        $event,
377
        $callbackURL,
378
        $access_key = null,
379
        $host = null
380
    ) {
381
        $path = '/events/add';
382
        if ($bucket) {
383 9
            $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...
384
        }
385 9
        if ($name) {
386 9
            $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...
387
        }
388
        if ($prefix) {
389 12
            $params['prefix'] = $prefix;
390
        }
391 12
        if ($suffix) {
392 12
            $params['suffix'] = $suffix;
393 12
        }
394 8
        if ($callbackURL) {
395
            $params['callbackURL'] = $callbackURL;
396 8
        }
397
        if ($access_key) {
398
            $params['access_key'] = $access_key;
399 33
        }
400
        if ($host) {
401 33
            $params['host'] = $host;
402 33
        }
403 33
        $data = http_build_query($params);
404 9
        if ($event) {
405
            $eventpath = "";
406 30
            foreach ($event as $key => $value) {
407 30
                $eventpath .= "&event=$value";
408
            }
409
            $data .= $eventpath;
410 3
        }
411
        $info = $this->ucPost($path, $data);
412 3
        return $info;
413
    }
414
415
    /**
416 3
     * 更新bucket事件通知规则
417
     *
418 3
     * @param $bucket     空间名
419
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
420
     * 只能为字母、数字、下划线()
421
     * @param $prefix     同一个 bucket 里面前缀不能重复
422 6
     * @param $suffix      可选,文件配置的后缀
423
     * @param $event  事件类型,可以指定多个,包括 put,mkfile,delete,copy,move,append,disable,
424 6
     * enable,deleteMarkerCreate
425
     * @param $callbackURL 通知URL,可以指定多个,失败依次重试
426
     * @param $access_key 可选,设置的话会对通知请求用对应的ak、sk进行签名
427
     * @param $host 可选,通知请求的host
428 3
     *
429
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
430 3
     */
431
    public function updateBucketEvent(
432
        $bucket,
433
        $name,
434 3
        $prefix,
435
        $suffix,
436 3
        $event,
437
        $callbackURL,
438
        $access_key = null,
439
        $host = null
440
    ) {
441
        $path = '/events/update';
442
        if ($bucket) {
443
            $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...
444
        }
445
        if ($name) {
446
            $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...
447
        }
448
        if ($prefix) {
449
            $params['prefix'] = $prefix;
450
        }
451
        if ($suffix) {
452
            $params['suffix'] = $suffix;
453
        }
454
        if ($event) {
455
            $params['event'] = $event;
456
        }
457
        if ($callbackURL) {
458
            $params['callbackURL'] = $callbackURL;
459
        }
460
        if ($access_key) {
461
            $params['access_key'] = $access_key;
462
        }
463
        if ($host) {
464
            $params['host'] = $host;
465
        }
466 6
        $data = http_build_query($params);
467
        $info = $this->ucPost($path, $data);
468 6
        return $info;
469 6
    }
470 6
471 6
    /**
472 6
     * 获取bucket事件通知规则
473
     *
474
     * @param $bucket     空间名
475 9
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
476
     */
477 9
    public function getBucketEvents($bucket)
478
    {
479
        $path = '/events/get?bucket=' . $bucket;
480 9
        $info = $this->ucGet($path);
481 9
        return $info;
482 9
    }
483 9
484 9
    /**
485 9
     * 删除bucket事件通知规则
486 9
     *
487 9
     * @param $bucket     空间名
488 9
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
489 9
     * 只能为字母、数字、下划线
490 9
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
491
     */
492
    public function deleteBucketEvent($bucket, $name)
493
    {
494
        $path = '/events/delete';
495
        if ($bucket) {
496
            $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...
497
        }
498
        if ($name) {
499
            $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...
500
        }
501
        $data = http_build_query($params);
502
        $info = $this->ucPost($path, $data);
503
        return $info;
504
    }
505
506
    /**
507
     * 设置bucket的跨域信息,最多允许设置10条跨域规则。
508
     * 对于同一个域名如果设置了多条规则,那么按顺序使用第一条匹配的规则去生成返回值。
509
     * 对于简单跨域请求,只匹配 Origin;
510
     * 对于预检请求, 需要匹配 Origin、AllowedMethod、AllowedHeader;
511
     * allowed_orgin: 允许的域名。必填;支持通配符*;*表示全部匹配;只有第一个*生效;
512
     * 需要设置"Scheme";大小写敏感。例如
513
     * 规则:http://*.abc.*.com 请求:"http://test.abc.test.com" 结果:不通过
514
     * 规则:"http://abc.com" 请求:"https://abc.com"/"abc.com" 结果:不通过
515
     * 规则:"abc.com" 请求:"http://abc.com" 结果:不通过
516
     * allowed_method: 允许的方法。必填;不支持通配符;大小写不敏感;
517
     * allowed_header: 允许的header。选填;支持通配符*,
518
     * 但只能是单独的*,表示允许全部header,其他*不生效;
519
     * 空则不允许任何header;大小写不敏感;
520
     * exposed_header: 暴露的header。选填;不支持通配符;
521
     * X-Log, X-Reqid是默认会暴露的两个header;
522
     * 其他的header如果没有设置,则不会暴露;大小写不敏感;
523
     * max_age: 结果可以缓存的时间。选填;空则不缓存;
524
     * allowed_credentials:该配置不支持设置,默认为true。
525
     * 备注:如果没有设置任何corsRules,那么默认允许所有的跨域请求
526
     */
527
    public function putCorsRules($bucket, $params)
528
    {
529
        $path = '/corsRules/set/' . $bucket;
530
        $data = json_encode($params);
531
        $info = $this->ucPost($path, $data);
532
        return $info;
533
    }
534
535
    /**
536
     * 获取bucket的跨域信息
537
     * $bucket 空间名
538
     */
539
    public function getCorsRules($bucket)
540
    {
541
        $path = '/corsRules/get/' . $bucket;
542
        $info = $this->ucGet($path);
543
        return $info;
544
    }
545
546
    /**
547
     * 设置回源规则
548
     * 使用该API设置源站优先级高于/image设置的源站,即IO优先读取source接口设置的源站配置,
549
     * 如果存在会忽略/image设置的源站
550
     * Bucket 空间名
551
     * Host(可选)回源Host
552
     * RetryCodes(可选),镜像回源时源站返回Code可以重试,最多指定3个,当前只支持4xx错误码重试
553
     * SourceQiniuAK,SourceQiniuSK(可选)如果存在将在回源时对URL进行签名,客户源站可以验证
554
     * 以保证请求来自Qiniu服务器
555
     * Expires(可选) 签名过期时间,如果不设置默认为1小时
556
     * Addr 回源地址,不可重复。
557
     * Weight 权重,范围限制1-100,不填默认为1,回源时会根据所有源的权重值进行源站选择,
558
     * 主备源会分开计算.
559
     * Backup 是否备用回源,回源优先尝试主源
560
     */
561
    public function putBucktSourceConfig(array $params)
562
    {
563
        $path = '/mirrorConfig/set';
564
        $data = json_encode($params);
565
        $info = $this->ucPostV2($path, $data);
566
        return $info;
567
    }
568
569
    /**
570
     * 获取空间回源配置
571
     */
572
    public function getBucktSourceConfig(array $params)
573
    {
574
        $path = '/mirrorConfig/get';
575
        $data = json_encode($params);
576
        $info = $this->ucPostV2($path, $data);
577
        return $info;
578
    }
579
580
    /**
581
     * 开关原图保护
582
     * mode 为1表示开启原图保护,0表示关闭
583
     */
584
    public function putBucketAccessStyleMode($bucket, $mode)
585
    {
586
        $path = '/accessMode/' . $bucket . '/mode/' . $mode;
587
        $info = $this->ucPost($path, null);
588
        return $info;
589
    }
590
591
    /**
592
     * 设置私有属性
593
     * private为0表示公开,为1表示私有
594
     */
595
    public function putBucketAccessMode($bucket, $private)
596
    {
597
        $path = '/bucket/' . $bucket . '/private/' . $private;
598
        $info = $this->ucPost($path, null);
599
        return $info;
600
    }
601
602
    /**
603
     * 设置referer防盗链
604
     * bucket=<BucketName>: bucket 名
605
     * mode=<AntiLeechMode>:
606
     * 0: 表示关闭Referer(使用此选项将会忽略以下参数并将恢复默认值);
607
     * 1: 表示设置Referer白名单; 2: 表示设置Referer黑名单
608
     * norefer=<NoRefer>: 0: 表示不允许空 Refer 访问;
609
     * 1: 表示允许空 Refer 访问
610
     * pattern=<Pattern>: 规则字符串, 当前允许格式分为三种:
611
     * 一种为空主机头域名, 比如 foo.com;
612
     * 一种是泛域名, 比如 *.bar.com; 一种是完全通配符, 即一个 *;
613
     * 多个规则之间用;隔开, 比如: foo.com;*.bar.com;sub.foo.com;*.sub.bar.com
614
     * 空主机头域名可以是多级域名,比如 foo.bar.com。
615
     * 多个域名之间不允许夹带空白字符。
616
     * source_enabled=:1
617
     */
618
    public function putReferAntiLeech($bucket, $mode, $norefer, $pattern, $enabled = 1)
619
    {
620
        $path = "/referAntiLeech?bucket=$bucket&mode=$mode&norefer=$norefer&pattern=$pattern&source_enabled=$enabled";
621
        $info = $this->ucPost($path, null);
622
        return $info;
623
    }
624
625
    /**
626
     * 设置Bucket的maxAge
627
     * maxAge为0或者负数表示为默认值(31536000)
628
     */
629
    public function putBucketMaxAge($bucket, $maxAge)
630
    {
631
        $path = '/maxAge?bucket=' . $bucket . '&maxAge=' . $maxAge;
632
        $info = $this->ucPost($path, null);
633
        return $info;
634
    }
635
636
    /**
637
     * 设置配额
638
     * <bucket>: 空间名称,不支持授权空间
639
     * <size>: 空间存储量配额,参数传入0或不传表示不更改当前配置,传入-1表示取消限额,
640
     * 新创建的空间默认没有限额。
641
     * <count>: 空间文件数配额,参数含义同<size>
642
     */
643
    public function putBucketQuota($bucket, $size, $count)
644
    {
645
        $path = '/setbucketquota/' . $bucket . '/size/' . $size . '/count/' . $count;
646
        $info = $this->apiPost($path, null);
647
        return $info;
648
    }
649
650
    /**
651
     * 获取配额
652
     * bucket 空间名称
653
     */
654
    public function getBucketQuota($bucket)
655
    {
656
        $path = '/getbucketquota/' . $bucket;
657
        $info = $this->apiPost($path, null);
658
        return $info;
659
    }
660
661
    /**
662
     * 获取资源的元信息,但不返回文件内容
663
     *
664
     * @param $bucket     待获取信息资源所在的空间
665
     * @param $key        待获取资源的文件名
666
     *
667
     * @return array    包含文件信息的数组,类似:
668
*                                              [
669
*                                                  "hash" => "<Hash string>",
670
*                                                  "key" => "<Key string>",
671
*                                                  "fsize" => <file size>,
672
*                                                  "putTime" => "<file modify time>"
673
*                                                  "fileType" => <file type>
674
*                                              ]
675
     *
676
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
677
     */
678
    public function stat($bucket, $key)
679
    {
680
        $path = '/stat/' . \Qiniu\entry($bucket, $key);
681
        return $this->rsGet($path);
682
    }
683
684
    /**
685
     * 删除指定资源
686
     *
687
     * @param $bucket     待删除资源所在的空间
688
     * @param $key        待删除资源的文件名
689
     *
690
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
691
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
692
     */
693
    public function delete($bucket, $key)
694
    {
695
        $path = '/delete/' . \Qiniu\entry($bucket, $key);
696
        list(, $error) = $this->rsPost($path);
697
        return $error;
698
    }
699
700
701
    /**
702
     * 给资源进行重命名,本质为move操作。
703
     *
704
     * @param $bucket     待操作资源所在空间
705
     * @param $oldname    待操作资源文件名
706
     * @param $newname    目标资源文件名
707
     *
708
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
709
     */
710
    public function rename($bucket, $oldname, $newname)
711
    {
712
        return $this->move($bucket, $oldname, $bucket, $newname);
713
    }
714
715
    /**
716
     * 对资源进行复制。
717
     *
718
     * @param $from_bucket     待操作资源所在空间
719
     * @param $from_key        待操作资源文件名
720
     * @param $to_bucket       目标资源空间名
721
     * @param $to_key          目标资源文件名
722
     *
723
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
724
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/copy.html
725
     */
726
    public function copy($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
727
    {
728
        $from = \Qiniu\entry($from_bucket, $from_key);
729
        $to = \Qiniu\entry($to_bucket, $to_key);
730
        $path = '/copy/' . $from . '/' . $to;
731
        if ($force === true) {
732
            $path .= '/force/true';
733
        }
734
        list(, $error) = $this->rsPost($path);
735
        return $error;
736
    }
737
738
    /**
739
     * 将资源从一个空间到另一个空间
740
     *
741
     * @param $from_bucket     待操作资源所在空间
742
     * @param $from_key        待操作资源文件名
743
     * @param $to_bucket       目标资源空间名
744
     * @param $to_key          目标资源文件名
745
     *
746
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
747
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
748
     */
749
    public function move($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
750
    {
751
        $from = \Qiniu\entry($from_bucket, $from_key);
752
        $to = \Qiniu\entry($to_bucket, $to_key);
753
        $path = '/move/' . $from . '/' . $to;
754
        if ($force) {
755
            $path .= '/force/true';
756
        }
757
        list(, $error) = $this->rsPost($path);
758
        return $error;
759
    }
760
761
    /**
762
     * 主动修改指定资源的文件元信息
763
     *
764
     * @param $bucket     待操作资源所在空间
765
     * @param $key        待操作资源文件名
766
     * @param $mime       待操作文件目标mimeType
767
     *
768
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
769
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
770
     */
771
    public function changeMime($bucket, $key, $mime)
772
    {
773
        $resource = \Qiniu\entry($bucket, $key);
774
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
775
        $path = '/chgm/' . $resource . '/mime/' . $encode_mime;
776
        list(, $error) = $this->rsPost($path);
777
        return $error;
778
    }
779
780
781
    /**
782
     * 修改指定资源的存储类型
783
     *
784
     * @param $bucket     待操作资源所在空间
785
     * @param $key        待操作资源文件名
786
     * @param $fileType       待操作文件目标文件类型
787
     *
788
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
789
     * @link  https://developer.qiniu.com/kodo/api/3710/modify-the-file-type
790
     */
791
    public function changeType($bucket, $key, $fileType)
792
    {
793
        $resource = \Qiniu\entry($bucket, $key);
794
        $path = '/chtype/' . $resource . '/type/' . $fileType;
795
        list(, $error) = $this->rsPost($path);
796
        return $error;
797
    }
798
799
    /**
800
     * 修改文件的存储状态,即禁用状态和启用状态间的的互相转换
801
     *
802
     * @param $bucket     待操作资源所在空间
803
     * @param $key        待操作资源文件名
804
     * @param $status       待操作文件目标文件类型
805
     *
806
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
807
     * @link  https://developer.qiniu.com/kodo/api/4173/modify-the-file-status
808
     */
809
    public function changeStatus($bucket, $key, $status)
810
    {
811
        $resource = \Qiniu\entry($bucket, $key);
812
        $path = '/chstatus/' . $resource . '/status/' . $status;
813
        list(, $error) = $this->rsPost($path);
814
        return $error;
815
    }
816
817
    /**
818
     * 从指定URL抓取资源,并将该资源存储到指定空间中
819
     *
820
     * @param $url        指定的URL
821
     * @param $bucket     目标资源空间
822
     * @param $key        目标资源文件名
823
     *
824
     * @return array    包含已拉取的文件信息。
825
     *                         成功时:  [
826
     *                                          [
827
     *                                              "hash" => "<Hash string>",
828
     *                                              "key" => "<Key string>"
829
     *                                          ],
830
     *                                          null
831
     *                                  ]
832
     *
833
     *                         失败时:  [
834
     *                                          null,
835
     *                                         Qiniu/Http/Error
836
     *                                  ]
837
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
838
     */
839
    public function fetch($url, $bucket, $key = null)
840
    {
841
842
        $resource = \Qiniu\base64_urlSafeEncode($url);
843
        $to = \Qiniu\entry($bucket, $key);
844
        $path = '/fetch/' . $resource . '/to/' . $to;
845
846
        $ak = $this->auth->getAccessKey();
847
        $ioHost = $this->config->getIovipHost($ak, $bucket);
848
849
        $url = $ioHost . $path;
850
        return $this->post($url, null);
851
    }
852
853
    /**
854
     * 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源
855
     *
856
     * @param $bucket     待获取资源所在的空间
857
     * @param $key        代获取资源文件名
858
     *
859
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
860
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
861
     */
862
    public function prefetch($bucket, $key)
863
    {
864
        $resource = \Qiniu\entry($bucket, $key);
865
        $path = '/prefetch/' . $resource;
866
867
        $ak = $this->auth->getAccessKey();
868
        $ioHost = $this->config->getIovipHost($ak, $bucket);
869
870
        $url = $ioHost . $path;
871
        list(, $error) = $this->post($url, null);
872
        return $error;
873
    }
874
875
    /**
876
     * 在单次请求中进行多个资源管理操作
877
     *
878
     * @param $operations     资源管理操作数组
879
     *
880
     * @return array 每个资源的处理情况,结果类似:
881
     *              [
882
     *                   { "code" => <HttpCode int>, "data" => <Data> },
883
     *                   { "code" => <HttpCode int> },
884
     *                   { "code" => <HttpCode int> },
885
     *                   { "code" => <HttpCode int> },
886
     *                   { "code" => <HttpCode int>, "data" => { "error": "<ErrorMessage string>" } },
887
     *                   ...
888
     *               ]
889
     * @link http://developer.qiniu.com/docs/v6/api/reference/rs/batch.html
890
     */
891
    public function batch($operations)
892
    {
893
        $params = 'op=' . implode('&op=', $operations);
894
        return $this->rsPost('/batch', $params);
895
    }
896
897
    /**
898
     * 设置文件的生命周期
899
     *
900
     * @param $bucket 设置文件生命周期文件所在的空间
901
     * @param $key    设置文件生命周期文件的文件名
902
     * @param $days   设置该文件多少天后删除,当$days设置为0时表示取消该文件的生命周期
903
     *
904
     * @return Mixed
905
     * @link https://developer.qiniu.com/kodo/api/update-file-lifecycle
906
     */
907
    public function deleteAfterDays($bucket, $key, $days)
908
    {
909
        $entry = \Qiniu\entry($bucket, $key);
910
        $path = "/deleteAfterDays/$entry/$days";
911
        list(, $error) = $this->rsPost($path);
912
        return $error;
913
    }
914
915
    private function getRsfHost()
916
    {
917
        $scheme = "http://";
918
        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...
919
            $scheme = "https://";
920
        }
921
        return $scheme . Config::RSF_HOST;
922
    }
923
924
    private function getRsHost()
925
    {
926
        $scheme = "http://";
927
        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...
928
            $scheme = "https://";
929
        }
930
        return $scheme . Config::RS_HOST;
931
    }
932
933
    private function getApiHost()
934
    {
935
        $scheme = "http://";
936
        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...
937
            $scheme = "https://";
938
        }
939
        return $scheme . Config::API_HOST;
940
    }
941
942
    private function getUcHost()
943
    {
944
        $scheme = "http://";
945
        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...
946
            $scheme = "https://";
947
        }
948
        return $scheme . Config::UC_HOST;
949
    }
950
951
    private function rsPost($path, $body = null)
952
    {
953
        $url = $this->getRsHost() . $path;
954
        return $this->post($url, $body);
955
    }
956
957
    private function apiPost($path, $body = null)
958
    {
959
        $url = $this->getApiHost() . $path;
960
        return $this->post($url, $body);
961
    }
962
963
    private function ucPost($path, $body = null)
964
    {
965
        $url = $this->getUcHost() . $path;
966
        return $this->post($url, $body);
967
    }
968
969
    private function ucGet($path)
970
    {
971
        $url = $this->getUcHost() . $path;
972
        return $this->get($url);
973
    }
974
975
    private function apiGet($path)
976
    {
977
        $url = $this->getApiHost() . $path;
978
        return $this->get($url);
979
    }
980
981
    private function rsGet($path)
982
    {
983
        $url = $this->getRsHost() . $path;
984
        return $this->get($url);
985
    }
986
987
    private function get($url)
988
    {
989
        $headers = $this->auth->authorization($url);
990
        $ret = Client::get($url, $headers);
991
        if (!$ret->ok()) {
992
            return array(null, new Error($url, $ret));
993
        }
994
        return array($ret->json(), null);
995
    }
996
997
    private function post($url, $body)
998
    {
999
        $headers = $this->auth->authorization($url, $body, 'application/x-www-form-urlencoded');
1000
        $ret = Client::post($url, $body, $headers);
1001
        if (!$ret->ok()) {
1002
            return array(null, new Error($url, $ret));
1003
        }
1004
        $r = ($ret->body === null) ? array() : $ret->json();
1005
        return array($r, null);
1006
    }
1007
1008
    private function ucPostV2($path, $body)
1009
    {
1010
        $url = $this->getUcHost() . $path;
1011
        return $this->postV2($url, $body);
1012
    }
1013
1014
    private function postV2($url, $body)
1015
    {
1016
        $headers = $this->auth->authorizationV2($url, 'POST', $body, 'application/json');
1017
        $headers["Content-Type"] = 'application/json';
1018
        $ret = Client::post($url, $body, $headers);
1019
        if (!$ret->ok()) {
1020
            return array(null, new Error($url, $ret));
1021
        }
1022
        $r = ($ret->body === null) ? array() : $ret->json();
1023
        return array($r, null);
1024
    }
1025
1026
    public static function buildBatchCopy($source_bucket, $key_pairs, $target_bucket, $force)
1027
    {
1028
        return self::twoKeyBatch('/copy', $source_bucket, $key_pairs, $target_bucket, $force);
1029
    }
1030
1031
1032
    public static function buildBatchRename($bucket, $key_pairs, $force)
1033
    {
1034
        return self::buildBatchMove($bucket, $key_pairs, $bucket, $force);
1035
    }
1036
1037
1038
    public static function buildBatchMove($source_bucket, $key_pairs, $target_bucket, $force)
1039
    {
1040
        return self::twoKeyBatch('/move', $source_bucket, $key_pairs, $target_bucket, $force);
1041
    }
1042
1043
1044
    public static function buildBatchDelete($bucket, $keys)
1045
    {
1046
        return self::oneKeyBatch('/delete', $bucket, $keys);
1047
    }
1048
1049
1050
    public static function buildBatchStat($bucket, $keys)
1051
    {
1052
        return self::oneKeyBatch('/stat', $bucket, $keys);
1053
    }
1054
1055
    public static function buildBatchDeleteAfterDays($bucket, $key_day_pairs)
1056
    {
1057
        $data = array();
1058
        foreach ($key_day_pairs as $key => $day) {
1059
            array_push($data, '/deleteAfterDays/' . \Qiniu\entry($bucket, $key) . '/' . $day);
1060
        }
1061
        return $data;
1062
    }
1063
1064
    public static function buildBatchChangeMime($bucket, $key_mime_pairs)
1065
    {
1066
        $data = array();
1067
        foreach ($key_mime_pairs as $key => $mime) {
1068
            array_push($data, '/chgm/' . \Qiniu\entry($bucket, $key) . '/mime/' . base64_encode($mime));
1069
        }
1070
        return $data;
1071
    }
1072
1073
    public static function buildBatchChangeType($bucket, $key_type_pairs)
1074
    {
1075
        $data = array();
1076
        foreach ($key_type_pairs as $key => $type) {
1077
            array_push($data, '/chtype/' . \Qiniu\entry($bucket, $key) . '/type/' . $type);
1078
        }
1079
        return $data;
1080
    }
1081
1082
    private static function oneKeyBatch($operation, $bucket, $keys)
1083
    {
1084
        $data = array();
1085
        foreach ($keys as $key) {
1086
            array_push($data, $operation . '/' . \Qiniu\entry($bucket, $key));
1087
        }
1088
        return $data;
1089
    }
1090
1091
    private static function twoKeyBatch($operation, $source_bucket, $key_pairs, $target_bucket, $force)
1092
    {
1093
        if ($target_bucket === null) {
1094
            $target_bucket = $source_bucket;
1095
        }
1096
        $data = array();
1097
        $forceOp = "false";
1098
        if ($force) {
1099
            $forceOp = "true";
1100
        }
1101
        foreach ($key_pairs as $from_key => $to_key) {
1102
            $from = \Qiniu\entry($source_bucket, $from_key);
1103
            $to = \Qiniu\entry($target_bucket, $to_key);
1104
            array_push($data, $operation . '/' . $from . '/' . $to . "/force/" . $forceOp);
1105
        }
1106
        return $data;
1107
    }
1108
}
1109