Completed
Pull Request — master (#213)
by r
23:00
created

BucketManager::buildBatchStat()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.0156

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 4
cp 0.75
crap 1.0156
rs 10
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 http://developer.qiniu.com/docs/v6/api/reference/rs/
14
 */
15
final class BucketManager
16
{
17
    private $auth;
18
    private $zone;
19
20 39
    public function __construct(Auth $auth, Zone $zone = null)
21
    {
22 39
        $this->auth = $auth;
23 39
        if ($zone === null) {
24 39
            $this->zone = new Zone();
25 26
        }
26 39
    }
27
28
    /**
29
     * 获取指定账号下所有的空间名。
30
     *
31
     * @return string[] 包含所有空间名
32
     */
33 3
    public function buckets()
34
    {
35 3
        return $this->rsGet('/buckets');
36
    }
37
38
    /**
39
     * 列取空间的文件列表
40
     *
41
     * @param $bucket     空间名
42
     * @param $prefix     列举前缀
43
     * @param $marker     列举标识符
44
     * @param $limit      单次列举个数限制
45
     * @param $delimiter  指定目录分隔符
46
     *
47
     * @return array    包含文件信息的数组,类似:[
48
     *                                              {
49
     *                                                 "hash" => "<Hash string>",
50
     *                                                  "key" => "<Key string>",
51
     *                                                  "fsize" => "<file size>",
52
     *                                                  "putTime" => "<file modify time>"
53
     *                                              },
54
     *                                              ...
55
     *                                            ]
56
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
57
     */
58 3
    public function listFiles($bucket, $prefix = null, $marker = null, $limit = 1000, $delimiter = null)
59
    {
60 3
        $query = array('bucket' => $bucket);
61 3
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
62 3
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
63 3
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
64 3
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
65 3
        $url = Config::RSF_HOST . '/list?' . http_build_query($query);
66 3
        list($ret, $error) = $this->get($url);
67 3
        if ($ret === null) {
68
            return array(null, null, $error);
69
        }
70 3
        $marker = array_key_exists('marker', $ret) ? $ret['marker'] : null;
71 3
        return array($ret['items'], $marker, null);
72
    }
73
74
    /**
75
     * 获取资源的元信息,但不返回文件内容
76
     *
77
     * @param $bucket     待获取信息资源所在的空间
78
     * @param $key        待获取资源的文件名
79
     *
80
     * @return array    包含文件信息的数组,类似:
81
     *                                              [
82
     *                                                  "hash" => "<Hash string>",
83
     *                                                  "key" => "<Key string>",
84
     *                                                  "fsize" => "<file size>",
85
     *                                                  "putTime" => "<file modify time>"
86
     *                                              ]
87
     *
88
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
89
     */
90 6
    public function stat($bucket, $key)
91
    {
92 6
        $path = '/stat/' . \Qiniu\entry($bucket, $key);
93 6
        return $this->rsGet($path);
94
    }
95
96
    /**
97
     * 删除指定资源
98
     *
99
     * @param $bucket     待删除资源所在的空间
100
     * @param $key        待删除资源的文件名
101
     *
102
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
103
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
104
     */
105 15
    public function delete($bucket, $key)
106
    {
107 15
        $path = '/delete/' . \Qiniu\entry($bucket, $key);
108 15
        list(, $error) = $this->rsPost($path);
109 15
        return $error;
110
    }
111
112
113
    /**
114
     * 给资源进行重命名,本质为move操作。
115
     *
116
     * @param $bucket     待操作资源所在空间
117
     * @param $oldname    待操作资源文件名
118
     * @param $newname    目标资源文件名
119
     *
120
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
121
     */
122 3
    public function rename($bucket, $oldname, $newname)
123
    {
124 3
        return $this->move($bucket, $oldname, $bucket, $newname);
125
    }
126
127
    /**
128
     * 给资源进行重命名,本质为move操作。
129
     *
130
     * @param $from_bucket     待操作资源所在空间
131
     * @param $from_key        待操作资源文件名
132
     * @param $to_bucket       目标资源空间名
133
     * @param $to_key          目标资源文件名
134
     *
135
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
136
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/copy.html
137
     */
138 12
    public function copy($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
139
    {
140 12
        $from = \Qiniu\entry($from_bucket, $from_key);
141 12
        $to = \Qiniu\entry($to_bucket, $to_key);
142 12
        $path = '/copy/' . $from . '/' . $to;
143 12
        if ($force) {
144 3
            $path .= '/force/true';
145 2
        }
146 12
        list(, $error) = $this->rsPost($path);
147 12
        return $error;
148
    }
149
150
    /**
151
     * 将资源从一个空间到另一个空间
152
     *
153
     * @param $from_bucket     待操作资源所在空间
154
     * @param $from_key        待操作资源文件名
155
     * @param $to_bucket       目标资源空间名
156
     * @param $to_key          目标资源文件名
157
     *
158
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
159
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
160
     */
161 3
    public function move($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
162
    {
163 3
        $from = \Qiniu\entry($from_bucket, $from_key);
164 3
        $to = \Qiniu\entry($to_bucket, $to_key);
165 3
        $path = '/move/' . $from . '/' . $to;
166 3
        if ($force) {
167
            $path .= '/force/true';
168
        }
169 3
        list(, $error) = $this->rsPost($path);
170 3
        return $error;
171
    }
172
173
    /**
174
     * 主动修改指定资源的文件类型
175
     *
176
     * @param $bucket     待操作资源所在空间
177
     * @param $key        待操作资源文件名
178
     * @param $mime       待操作文件目标mimeType
179
     *
180
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
181
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
182
     */
183 3
    public function changeMime($bucket, $key, $mime)
184
    {
185 3
        $resource = \Qiniu\entry($bucket, $key);
186 3
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
187 3
        $path = '/chgm/' . $resource . '/mime/' .$encode_mime;
188 3
        list(, $error) = $this->rsPost($path);
189 3
        return $error;
190
    }
191
192
    /**
193
     * 从指定URL抓取资源,并将该资源存储到指定空间中
194
     *
195
     * @param $url        指定的URL
196
     * @param $bucket     目标资源空间
197
     * @param $key        目标资源文件名
198
     *
199
     * @return array    包含已拉取的文件信息。
200
     *                         成功时:  [
201
     *                                          [
202
     *                                              "hash" => "<Hash string>",
203
     *                                              "key" => "<Key string>"
204
     *                                          ],
205
     *                                          null
206
     *                                  ]
207
     *
208
     *                         失败时:  [
209
     *                                          null,
210
     *                                         Qiniu/Http/Error
211
     *                                  ]
212
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
213
     */
214 3
    public function fetch($url, $bucket, $key = null)
215
    {
216
217 3
        $resource = \Qiniu\base64_urlSafeEncode($url);
218 3
        $to = \Qiniu\entry($bucket, $key);
219 3
        $path = '/fetch/' . $resource . '/to/' . $to;
220
221 3
        $ak = $this->auth->getAccessKey();
222 3
        $ioHost = $this->zone->getIoHost($ak, $bucket);
223
224 3
        $url = $ioHost . $path;
225 3
        return $this->post($url, null);
226
    }
227
228
    /**
229
     * 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源
230
     *
231
     * @param $bucket     待获取资源所在的空间
232
     * @param $key        代获取资源文件名
233
     *
234
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
235
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
236
     */
237 3
    public function prefetch($bucket, $key)
238
    {
239 3
        $resource = \Qiniu\entry($bucket, $key);
240 3
        $path = '/prefetch/' . $resource;
241
242 3
        $ak = $this->auth->getAccessKey();
243 3
        $ioHost = $this->zone->getIoHost($ak, $bucket);
244
245 3
        $url = $ioHost . $path;
246 3
        list(, $error) = $this->post($url, null);
247 3
        return $error;
248
    }
249
250
    /**
251
     * 在单次请求中进行多个资源管理操作
252
     *
253
     * @param $operations     资源管理操作数组
254
     *
255
     * @return array 每个资源的处理情况,结果类似:
256
     *              [
257
     *                   { "code" => <HttpCode int>, "data" => <Data> },
258
     *                   { "code" => <HttpCode int> },
259
     *                   { "code" => <HttpCode int> },
260
     *                   { "code" => <HttpCode int> },
261
     *                   { "code" => <HttpCode int>, "data" => { "error": "<ErrorMessage string>" } },
262
     *                   ...
263
     *               ]
264
     * @link http://developer.qiniu.com/docs/v6/api/reference/rs/batch.html
265
     */
266 12
    public function batch($operations)
267
    {
268 12
        $params = 'op=' . implode('&op=', $operations);
269 12
        return $this->rsPost('/batch', $params);
270
    }
271
272 24
    /**
273
     * 设置文件的生命周期
274 24
     *
275 24
     * @param $bucket 设置文件生命周期文件所在的空间
276
     * @param $key    设置文件生命周期文件的文件名
277
     * @param $days   设置该文件多少天后删除,当$days设置为0时表示取消该文件的生命周期
278 9
     *
279
     * @return Mixed
280 9
     * @link https://developer.qiniu.com/kodo/api/update-file-lifecycle
281 9
     */
282
    public function deleteAfterDays($bucket, $key, $days)
283
    {
284
        $entry = \Qiniu\entry($bucket, $key);
285
        $url = "/deleteAfterDays/$entry/$days";
286
        list(, $error) = $this->rsPost($url);
287
        return $error;
288
    }
289
290 12
    private function rsPost($path, $body = null)
291
    {
292 12
        $url = Config::RS_HOST . $path;
293 12
        return $this->post($url, $body);
294 12
    }
295 6
296
    private function rsGet($path)
297 12
    {
298
        $url = Config::RS_HOST . $path;
299
        return $this->get($url);
300 30
    }
301
302 30
    private function ioPost($path, $body = null)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
303 30
    {
304 30
        $url = Config::IO_HOST . $path;
305 6
        return $this->post($url, $body);
306
    }
307 27
308 27
    private function get($url)
309
    {
310
        $headers = $this->auth->authorization($url);
311 3
        $ret = Client::get($url, $headers);
312
        if (!$ret->ok()) {
313 3
            return array(null, new Error($url, $ret));
314
        }
315
        return array($ret->json(), null);
316
    }
317 3
318
    private function post($url, $body)
319 3
    {
320
        $headers = $this->auth->authorization($url, $body, 'application/x-www-form-urlencoded');
321
        $ret = Client::post($url, $body, $headers);
322
        if (!$ret->ok()) {
323 6
            return array(null, new Error($url, $ret));
324
        }
325 6
        $r = ($ret->body === null) ? array() : $ret->json();
326
        return array($r, null);
327
    }
328
329 3
    public static function buildBatchCopy($source_bucket, $key_pairs, $target_bucket)
330
    {
331 3
        return self::twoKeyBatch('copy', $source_bucket, $key_pairs, $target_bucket);
332
    }
333
334
335 3
    public static function buildBatchRename($bucket, $key_pairs)
336
    {
337 3
        return self::buildBatchMove($bucket, $key_pairs, $bucket);
338
    }
339
340 6
341
    public static function buildBatchMove($source_bucket, $key_pairs, $target_bucket)
342 6
    {
343 6
        return self::twoKeyBatch('move', $source_bucket, $key_pairs, $target_bucket);
344 6
    }
345 4
346 6
347
    public static function buildBatchDelete($bucket, $keys)
348
    {
349 9
        return self::oneKeyBatch('delete', $bucket, $keys);
350
    }
351 9
352
353
    public static function buildBatchStat($bucket, $keys)
354 9
    {
355 9
        return self::oneKeyBatch('stat', $bucket, $keys);
356 9
    }
357 9
358 9
    private static function oneKeyBatch($operation, $bucket, $keys)
359 6
    {
360 9
        $data = array();
361
        foreach ($keys as $key) {
362
            array_push($data, $operation . '/' . \Qiniu\entry($bucket, $key));
363
        }
364
        return $data;
365
    }
366
367
    private static function twoKeyBatch($operation, $source_bucket, $key_pairs, $target_bucket)
368
    {
369
        if ($target_bucket === null) {
370
            $target_bucket = $source_bucket;
371
        }
372
        $data = array();
373
        foreach ($key_pairs as $from_key => $to_key) {
374
            $from = \Qiniu\entry($source_bucket, $from_key);
375
            $to = \Qiniu\entry($target_bucket, $to_key);
376
            array_push($data, $operation . '/' . $from . '/' . $to);
377
        }
378
        return $data;
379
    }
380
}
381