Completed
Push — master ( d3d542...2a3fa4 )
by frey
03:07
created

Adapter::readStream()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.5

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 2
cts 4
cp 0.5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2.5
1
<?php
2
3
namespace Freyo\Flysystem\QcloudCOSv5;
4
5
use Carbon\Carbon;
6
use DateTimeInterface;
7
use League\Flysystem\Adapter\AbstractAdapter;
8
use League\Flysystem\AdapterInterface;
9
use League\Flysystem\Config;
10
use Qcloud\Cos\Client;
11
use Qcloud\Cos\Exception\NoSuchKeyException;
12
13
/**
14
 * Class Adapter.
15
 */
16
class Adapter extends AbstractAdapter
17
{
18
    /**
19
     * @var Client
20
     */
21
    protected $client;
22
23
    /**
24
     * @var array
25
     */
26
    protected $config = [];
27
28
    /**
29
     * @var array
30
     */
31
    protected $regionMap = [
32
        'cn-east'      => 'ap-shanghai',
33
        'cn-sorth'     => 'ap-guangzhou',
34
        'cn-north'     => 'ap-beijing-1',
35
        'cn-south-2'   => 'ap-guangzhou-2',
36
        'cn-southwest' => 'ap-chengdu',
37
        'sg'           => 'ap-singapore',
38
        'tj'           => 'ap-beijing-1',
39
        'bj'           => 'ap-beijing',
40
        'sh'           => 'ap-shanghai',
41
        'gz'           => 'ap-guangzhou',
42
        'cd'           => 'ap-chengdu',
43
        'sgp'          => 'ap-singapore',
44
    ];
45
46
    /**
47
     * Adapter constructor.
48
     *
49
     * @param Client $client
50
     * @param array  $config
51
     */
52
    public function __construct(Client $client, array $config)
53
    {
54
        $this->client = $client;
55
        $this->config = $config;
56
57
        $this->setPathPrefix($config['cdn']);
58
    }
59
60
    /**
61
     * @return string
62
     */
63 18
    public function getBucket()
64
    {
65 18
        return $this->config['bucket'];
66
    }
67
68
    /**
69
     * @return string
70
     */
71 2
    public function getAppId()
72
    {
73 2
        return $this->config['credentials']['appId'];
74
    }
75
76
    /**
77
     * @return string
78
     */
79 2
    public function getRegion()
80
    {
81 2
        return array_key_exists($this->config['region'], $this->regionMap)
82 2
            ? $this->regionMap[$this->config['region']] : $this->config['region'];
83
    }
84
85
    /**
86
     * @param $path
87
     *
88
     * @return string
89
     */
90 2
    public function getSourcePath($path)
91
    {
92 2
        return sprintf('%s-%s.cos.%s.myqcloud.com/%s',
93 2
            $this->getBucket(), $this->getAppId(), $this->getRegion(), $path
94 2
        );
95
    }
96
97
    /**
98
     * @param string $path
99
     *
100
     * @return string
101
     */
102 6
    public function getUrl($path)
103
    {
104 6
        if ($this->config['cdn']) {
105 2
            return $this->applyPathPrefix($path);
106
        }
107
108
        return urldecode(
109
            $this->client->getObjectUrl(
110 4
                $this->getBucket(), $path, null, ['Scheme' => $this->config['scheme']]
111
            )
112
        );
113
    }
114
115
    /**
116
     * @param string             $path
117
     * @param \DateTimeInterface $expiration
118
     * @param array              $options
119
     *
120
     * @return string
121
     */
122
    public function getTemporaryUrl($path, DateTimeInterface $expiration, array $options = [])
123
    {
124
        $options = array_merge($options, ['Scheme' => $this->config['scheme']]);
125
126
        $objectUrl = urldecode(
127
            $this->client->getObjectUrl(
128
                $this->getBucket(), $path, $expiration->format('c'), $options
129
            )
130
        );
131
132
        if ($this->config['cdn']) {
133
            $url = parse_url($objectUrl);
134
            return $this->config['cdn'] . $url['path'] . '?' . $url['query'];
135
        }
136
137
        return $objectUrl;
138
    }
139
140
    /**
141
     * @param string $path
142
     * @param string $contents
143
     * @param Config $config
144
     *
145
     * @return array|bool
146
     */
147 2
    public function write($path, $contents, Config $config)
148
    {
149 2
        return $this->client->upload($this->getBucket(), $path, $contents);
150
    }
151
152
    /**
153
     * @param string   $path
154
     * @param resource $resource
155
     * @param Config   $config
156
     *
157
     * @return array|bool
158
     */
159 2
    public function writeStream($path, $resource, Config $config)
160
    {
161 2
        return $this->client->upload($this->getBucket(), $path, stream_get_contents($resource, -1, 0));
162
    }
163
164
    /**
165
     * @param string $path
166
     * @param string $contents
167
     * @param Config $config
168
     *
169
     * @return array|bool
170
     */
171 1
    public function update($path, $contents, Config $config)
172
    {
173 1
        return $this->write($path, $contents, $config);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->write($path, $contents, $config); of type array|boolean adds the type boolean to the return on line 173 which is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::update of type array|false.
Loading history...
174
    }
175
176
    /**
177
     * @param string   $path
178
     * @param resource $resource
179
     * @param Config   $config
180
     *
181
     * @return array|bool
182
     */
183 1
    public function updateStream($path, $resource, Config $config)
184
    {
185 1
        return $this->writeStream($path, $resource, $config);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->writeStream($path, $resource, $config); of type array|boolean adds the type boolean to the return on line 185 which is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::updateStream of type array|false.
Loading history...
186
    }
187
188
    /**
189
     * @param string $path
190
     * @param string $newpath
191
     *
192
     * @return bool
193
     */
194 1
    public function rename($path, $newpath)
195
    {
196 1
        $source = $this->getSourcePath($path);
197
198 1
        $response = $this->client->copyObject([
199 1
            'Bucket'     => $this->getBucket(),
200 1
            'Key'        => $newpath,
201 1
            'CopySource' => $source,
202 1
        ]);
203
204
        $this->delete($path);
205
206
        return (bool) $response;
207
    }
208
209
    /**
210
     * @param string $path
211
     * @param string $newpath
212
     *
213
     * @return bool
214
     */
215 1
    public function copy($path, $newpath)
216
    {
217 1
        $source = $this->getSourcePath($path);
218
219 1
        return (bool) $this->client->copyObject([
220 1
            'Bucket'     => $this->getBucket(),
221 1
            'Key'        => $newpath,
222 1
            'CopySource' => $source,
223 1
        ]);
224
    }
225
226
    /**
227
     * @param string $path
228
     *
229
     * @return bool
230
     */
231 1
    public function delete($path)
232
    {
233 1
        return (bool) $this->client->deleteObject([
234 1
            'Bucket' => $this->getBucket(),
235 1
            'Key'    => $path,
236 1
        ]);
237
    }
238
239
    /**
240
     * @param string $dirname
241
     *
242
     * @return bool
243
     */
244 1
    public function deleteDir($dirname)
245
    {
246 1
        $response = $this->listObjects($dirname);
247
248
        if (!isset($response['Contents'])) {
249
            return true;
250
        }
251
252
        $keys = array_map(function ($item) {
253
            return ['Key' => $item['Key']];
254
        }, (array) $response['Contents']);
255
256
        return (bool) $this->client->deleteObjects([
257
            'Bucket'  => $this->getBucket(),
258
            'Objects' => $keys,
259
        ]);
260
    }
261
262
    /**
263
     * @param string $dirname
264
     * @param Config $config
265
     *
266
     * @return array|bool
267
     */
268 1
    public function createDir($dirname, Config $config)
269
    {
270 1
        return $this->client->putObject([
271 1
            'Bucket' => $this->getBucket(),
272 1
            'Key'    => $dirname.'/_blank',
273 1
            'Body'   => '',
274 1
        ]);
275
    }
276
277
    /**
278
     * @param string $path
279
     * @param string $visibility
280
     *
281
     * @return bool
282
     */
283 1
    public function setVisibility($path, $visibility)
284
    {
285 1
        $visibility = ($visibility === AdapterInterface::VISIBILITY_PUBLIC)
286 1
            ? 'public-read' : 'private';
287
288 1
        return (bool) $this->client->PutObjectAcl([
0 ignored issues
show
Bug Best Practice introduced by
The return type of return (bool) $this->cli...'ACL' => $visibility)); (boolean) is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::setVisibility of type array|false.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
289 1
            'Bucket' => $this->getBucket(),
290 1
            'Key'    => $path,
291 1
            'ACL'    => $visibility,
292 1
        ]);
293
    }
294
295
    /**
296
     * @param string $path
297
     *
298
     * @return bool
299
     */
300 1
    public function has($path)
301
    {
302
        try {
303 1
            return (bool) $this->getMetadata($path);
304 1
        } catch (NoSuchKeyException $e) {
305
            return false;
306
        }
307
    }
308
309
    /**
310
     * @param string $path
311
     *
312
     * @return array|bool
313
     */
314 1
    public function read($path)
315
    {
316
        try {
317 1
            $response = $this->client->getObject([
0 ignored issues
show
Bug introduced by
The method getObject() does not exist on Qcloud\Cos\Client. Did you maybe mean getObjectUrl()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
318 1
                'Bucket' => $this->getBucket(),
319 1
                'Key'    => $path,
320 1
            ]);
321
322
            return ['contents' => (string) $response->get('Body')];
323 1
        } catch (NoSuchKeyException $e) {
324
            return false;
325
        }
326
    }
327
328
    /**
329
     * @param string $path
330
     *
331
     * @return array|bool
332
     */
333 1
    public function readStream($path)
334
    {
335
        try {
336 1
            return ['stream' => fopen($this->getUrl($path), 'rb', false)];
337
        } catch (NoSuchKeyException $e) {
338
            return false;
339
        }
340
    }
341
342
    /**
343
     * @param string $directory
344
     * @param bool   $recursive
345
     *
346
     * @return array|bool
347
     */
348 1
    public function listContents($directory = '', $recursive = false)
349
    {
350 1
        $list = [];
351
352 1
        $response = $this->listObjects($directory, $recursive);
353
354
        foreach ((array) $response->get('Contents') as $content) {
355
            $list[] = $this->normalizeFileInfo($content);
356
        }
357
358
        return $list;
359
    }
360
361
    /**
362
     * @param string $path
363
     *
364
     * @return array|bool
365
     */
366 5
    public function getMetadata($path)
367
    {
368 5
        return $this->client->headObject([
369 5
            'Bucket' => $this->getBucket(),
370 5
            'Key'    => $path,
371 5
        ])->toArray();
372
    }
373
374
    /**
375
     * @param string $path
376
     *
377
     * @return array|bool
378
     */
379 1
    public function getSize($path)
380
    {
381 1
        $meta = $this->getMetadata($path);
382
383
        return isset($meta['ContentLength'])
384
            ? ['size' => $meta['ContentLength']] : false;
385
    }
386
387
    /**
388
     * @param string $path
389
     *
390
     * @return array|bool
391
     */
392 1
    public function getMimetype($path)
393
    {
394 1
        $meta = $this->getMetadata($path);
395
396
        return isset($meta['ContentType'])
397
            ? ['mimetype' => $meta['ContentType']] : false;
398
    }
399
400
    /**
401
     * @param string $path
402
     *
403
     * @return array|bool
404
     */
405 1
    public function getTimestamp($path)
406
    {
407 1
        $meta = $this->getMetadata($path);
408
409
        return isset($meta['LastModified'])
410
            ? ['timestamp' => strtotime($meta['LastModified'])] : false;
411
    }
412
413
    /**
414
     * @param string $path
415
     *
416
     * @return array|bool
417
     */
418 1
    public function getVisibility($path)
419
    {
420 1
        $meta = $this->client->getObjectAcl([
421 1
            'Bucket' => $this->getBucket(),
422 1
            'Key'    => $path,
423 1
        ]);
424
425
        foreach ($meta->get('Grants') as $grant) {
426
            if (isset($grant['Grantee']['URI'])
427
                && $grant['Permission'] === 'READ'
428
                && strpos($grant['Grantee']['URI'], 'global/AllUsers') !== false
429
            ) {
430
                return ['visibility' => AdapterInterface::VISIBILITY_PUBLIC];
431
            }
432
        }
433
434
        return ['visibility' => AdapterInterface::VISIBILITY_PRIVATE];
435
    }
436
437
    /**
438
     * @param array $content
439
     *
440
     * @return array
441
     */
442
    private function normalizeFileInfo(array $content)
443
    {
444
        $path = pathinfo($content['Key']);
445
446
        return [
447
            'type'      => 'file',
448
            'path'      => $content['Key'],
449
            'timestamp' => Carbon::parse($content['LastModified'])->getTimestamp(),
450
            'size'      => (int) $content['Size'],
451
            'dirname'   => (string) $path['dirname'],
452
            'basename'  => (string) $path['basename'],
453
            'extension' => isset($path['extension']) ? $path['extension'] : '',
454
            'filename'  => (string) $path['filename'],
455
        ];
456
    }
457
458
    /**
459
     * @param string $directory
460
     * @param bool   $recursive
461
     *
462
     * @return mixed
463
     */
464 2
    private function listObjects($directory = '', $recursive = false)
465
    {
466 2
        return $this->client->listObjects([
467 2
            'Bucket'    => $this->getBucket(),
468 2
            'Prefix'    => ((string) $directory === '') ? '' : ($directory.'/'),
469 2
            'Delimiter' => $recursive ? '' : '/',
470 2
        ]);
471
    }
472
}
473