Completed
Pull Request — master (#293)
by
unknown
10:59
created

BucketManager::bucketLifecycleRule()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

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