Passed
Push — master ( 87a025...da4c49 )
by frey
01:04
created

Adapter::normalizeFileInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 6
cp 0
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Freyo\Flysystem\QcloudCOSv5;
4
5
use DateTimeInterface;
6
use League\Flysystem\Adapter\AbstractAdapter;
7
use League\Flysystem\AdapterInterface;
8
use League\Flysystem\Config;
9
use Qcloud\Cos\Client;
10
use Qcloud\Cos\Exception\NoSuchKeyException;
11
12
/**
13
 * Class Adapter.
14
 */
15
class Adapter extends AbstractAdapter
16
{
17
    /**
18
     * @var Client
19
     */
20
    protected $client;
21
22
    /**
23
     * @var array
24
     */
25
    protected $config = [];
26
27
    /**
28
     * @var array
29
     */
30
    protected $regionMap = [
31
        'cn-east' => 'ap-shanghai',
32
        'cn-sorth' => 'ap-guangzhou',
33
        'cn-north' => 'ap-beijing-1',
34
        'cn-south-2' => 'ap-guangzhou-2',
35
        'cn-southwest' => 'ap-chengdu',
36
        'sg' => 'ap-singapore',
37
        'tj' => 'ap-beijing-1',
38
        'bj' => 'ap-beijing',
39
        'sh' => 'ap-shanghai',
40
        'gz' => 'ap-guangzhou',
41
        'cd' => 'ap-chengdu',
42
        'sgp' => 'ap-singapore',
43
    ];
44
45
    /**
46
     * Adapter constructor.
47
     *
48
     * @param Client $client
49
     * @param array $config
50
     */
51
    public function __construct(Client $client, array $config)
52
    {
53
        $this->client = $client;
54
        $this->config = $config;
55
56
        $this->setPathPrefix($config['cdn']);
57
    }
58
59
    /**
60
     * @return string
61
     */
62 18
    public function getBucket()
63
    {
64 18
        return $this->config['bucket'];
65
    }
66
67
    /**
68
     * @return string
69
     */
70 2
    public function getAppId()
71
    {
72 2
        return $this->config['credentials']['appId'];
73
    }
74
75
    /**
76
     * @return string
77
     */
78 2
    public function getRegion()
79
    {
80 2
        return $this->regionMap[$this->config['region']];
81
    }
82
83
    /**
84
     * @param $path
85
     *
86
     * @return string
87
     */
88 2
    public function getSourcePath($path)
89
    {
90 2
        return sprintf('%s-%s.cos.%s.myqcloud.com/%s',
91 2
            $this->getBucket(), $this->getAppId(), $this->getRegion(), $path
92 2
        );
93
    }
94
95
    /**
96
     * @param string $path
97
     *
98
     * @return string
99
     */
100 4
    public function getUrl($path)
101
    {
102 3
        if (!empty($this->config['cdn'])) {
103 2
            return $this->applyPathPrefix($path);
104 4
        }
105
106
        return urldecode(
107
            $this->client->getObjectUrl($this->getBucket(), $path)
108
        );
109
    }
110
111
    /**
112
     * @param  string $path
113
     * @param  \DateTimeInterface $expiration
114
     * @param  array $options
115
     *
116
     * @return string
117
     */
118
    public function getTemporaryUrl($path, DateTimeInterface $expiration, array $options = [])
119
    {
120
        return urldecode(
121
            $this->client->getObjectUrl(
122
                $this->getBucket(), $path, $expiration->format('Y-m-d H:i:s'), $options
123
            )
124
        );
125
    }
126
127
    /**
128
     * @param string $path
129
     * @param string $contents
130
     * @param Config $config
131
     *
132
     * @return array|bool
133
     */
134 2
    public function write($path, $contents, Config $config)
135
    {
136 2
        return $this->client->upload($this->getBucket(), $path, $contents);
137
    }
138
139
    /**
140
     * @param string $path
141
     * @param resource $resource
142
     * @param Config $config
143
     *
144
     * @return array|bool
145
     */
146 2
    public function writeStream($path, $resource, Config $config)
147
    {
148 2
        return $this->client->upload($this->getBucket(), $path, stream_get_contents($resource, -1, 0));
149
    }
150
151
    /**
152
     * @param string $path
153
     * @param string $contents
154
     * @param Config $config
155
     *
156
     * @return array|bool
157
     */
158 1
    public function update($path, $contents, Config $config)
159
    {
160 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 160 which is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::update of type array|false.
Loading history...
161
    }
162
163
    /**
164
     * @param string $path
165
     * @param resource $resource
166
     * @param Config $config
167
     *
168
     * @return array|bool
169
     */
170 1
    public function updateStream($path, $resource, Config $config)
171
    {
172 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 172 which is incompatible with the return type declared by the interface League\Flysystem\AdapterInterface::updateStream of type array|false.
Loading history...
173
    }
174
175
    /**
176
     * @param string $path
177
     * @param string $newpath
178
     *
179
     * @return bool
180
     */
181 1
    public function rename($path, $newpath)
182
    {
183 1
        $source = $this->getSourcePath($path);
184
185 1
        $response = $this->client->copyObject([
186 1
            'Bucket' => $this->getBucket(),
187 1
            'Key' => $newpath,
188 1
            'CopySource' => $source,
189 1
        ]);
190
191
        $this->delete($path);
192
193
        return (bool)$response;
194
    }
195
196
    /**
197
     * @param string $path
198
     * @param string $newpath
199
     *
200
     * @return bool
201
     */
202 1
    public function copy($path, $newpath)
203
    {
204 1
        $source = $this->getSourcePath($path);
205
206 1
        return (bool)$this->client->copyObject([
207 1
            'Bucket' => $this->getBucket(),
208 1
            'Key' => $newpath,
209 1
            'CopySource' => $source,
210 1
        ]);
211
    }
212
213
    /**
214
     * @param string $path
215
     *
216
     * @return bool
217
     */
218 1
    public function delete($path)
219
    {
220 1
        return (bool)$this->client->deleteObject([
221 1
            'Bucket' => $this->getBucket(),
222 1
            'Key' => $path,
223 1
        ]);
224
    }
225
226
    /**
227
     * @param string $dirname
228
     *
229
     * @return bool
230
     */
231 1
    public function deleteDir($dirname)
232
    {
233 1
        $response = $this->listContents($dirname);
234
235
        $keys = array_map(function ($item) {
236
            return ['Key' => $item['Key']];
237
        }, (array)$response['Contents']);
238
239
        return (bool)$this->client->deleteObjects([
240
            'Bucket' => $this->getBucket(),
241
            'Objects' => $keys,
242
        ]);
243
    }
244
245
    /**
246
     * @param string $dirname
247
     * @param Config $config
248
     *
249
     * @return array|bool
250
     */
251 1
    public function createDir($dirname, Config $config)
252
    {
253 1
        return $this->client->putObject([
254 1
            'Bucket' => $this->getBucket(),
255 1
            'Key' => $dirname . '/_blank',
256 1
            'Body' => '',
257 1
        ]);
258
    }
259
260
    /**
261
     * @param string $path
262
     * @param string $visibility
263
     *
264
     * @return bool
265
     */
266 1
    public function setVisibility($path, $visibility)
267
    {
268 1
        $visibility = ($visibility === AdapterInterface::VISIBILITY_PUBLIC)
269 1
            ? 'public-read' : 'private';
270
271 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...
272 1
            'Bucket' => $this->getBucket(),
273 1
            'Key' => $path,
274 1
            'ACL' => $visibility,
275 1
        ]);
276
    }
277
278
    /**
279
     * @param string $path
280
     *
281
     * @return bool
282
     */
283 1
    public function has($path)
284
    {
285
        try {
286 1
            return (bool)$this->getMetadata($path);
287 1
        } catch (NoSuchKeyException $e) {
288
            return false;
289
        }
290
    }
291
292
    /**
293
     * @param string $path
294
     *
295
     * @return array|bool
296
     */
297 1
    public function read($path)
298
    {
299
        try {
300 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...
301 1
                'Bucket' => $this->getBucket(),
302 1
                'Key' => $path,
303 1
            ]);
304
305
            return ['contents' => (string)$response->get('Body')];
306 1
        } catch (NoSuchKeyException $e) {
307
            return false;
308
        }
309
    }
310
311
    /**
312
     * @param string $path
313
     *
314
     * @return array|bool
315
     */
316 1
    public function readStream($path)
317
    {
318
        try {
319 1
            return ['stream' => fopen($this->getUrl($path), 'rb', false)];
320
        } catch (NoSuchKeyException $e) {
321
            return false;
322
        }
323
    }
324
325
    /**
326
     * @param string $directory
327
     * @param bool $recursive
328
     *
329
     * @return array|bool
330
     */
331 2
    public function listContents($directory = '', $recursive = false)
332
    {
333 2
        $list = [];
334
335 2
        $result = $this->client->listObjects([
336 2
            'Bucket' => $this->getBucket(),
337 2
            'Prefix' => $directory . '/',
338 2
            'Delimiter' => $recursive ? '' : '/',
339 2
        ])->toArray();
340
341
        $contents = isset($result['Contents']) ? $result['Contents'] : [];
342
        foreach ($contents as $content) {
343
            $list[] = $this->normalizeFileInfo($content);
344
        }
345
346
        return $list;
347
    }
348
349
    /**
350
     * @param string $path
351
     *
352
     * @return array|bool
353
     */
354 5
    public function getMetadata($path)
355
    {
356 5
        return $this->client->headObject([
357 5
            'Bucket' => $this->getBucket(),
358 5
            'Key' => $path,
359 5
        ])->toArray();
360
    }
361
362
    /**
363
     * @param string $path
364
     *
365
     * @return array|bool
366
     */
367 1
    public function getSize($path)
368
    {
369 1
        $meta = $this->getMetadata($path);
370
371
        return isset($meta['ContentLength'])
372
            ? ['size' => $meta['ContentLength']] : false;
373
    }
374
375
    /**
376
     * @param string $path
377
     *
378
     * @return array|bool
379
     */
380 1
    public function getMimetype($path)
381
    {
382 1
        $meta = $this->getMetadata($path);
383
384
        return isset($meta['ContentType'])
385
            ? ['mimetype' => $meta['ContentType']] : false;
386
    }
387
388
    /**
389
     * @param string $path
390
     *
391
     * @return array|bool
392
     */
393 1
    public function getTimestamp($path)
394
    {
395 1
        $meta = $this->getMetadata($path);
396
397
        return isset($meta['LastModified'])
398
            ? ['timestamp' => strtotime($meta['LastModified'])] : false;
399
    }
400
401
    /**
402
     * @param string $path
403
     *
404
     * @return array|bool
405
     */
406 1
    public function getVisibility($path)
407
    {
408 1
        $meta = $this->client->getObjectAcl([
409 1
            'Bucket' => $this->getBucket(),
410 1
            'Key' => $path,
411 1
        ]);
412
413
        foreach ($meta->get('Grants') as $grant) {
414
            if (isset($grant['Grantee']['URI'])
415
                && $grant['Permission'] === 'READ'
416
                && strpos($grant['Grantee']['URI'], 'global/AllUsers') !== false
417
            ) {
418
                return ['visibility' => AdapterInterface::VISIBILITY_PUBLIC];
419
            }
420
        }
421
422
        return ['visibility' => AdapterInterface::VISIBILITY_PRIVATE];
423
    }
424
425
    private function normalizeFileInfo(array $content)
426
    {
427
        return [
428
            'type' => 'file',
429
            'path' => $content['Key'],
430
            'timestamp' => \Carbon\Carbon::parse($content['LastModified'])->timestamp,
431
            'size' => (int)$content['Size'],
432
        ];
433
    }
434
}
435