Completed
Push — master ( dec506...6c3448 )
by frey
02:09
created

Adapter::getBucket()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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
        return $this->client->listObjects([
334 2
            'Bucket'    => $this->getBucket(),
335 2
            'Prefix'    => $directory.'/',
336 2
            'Delimiter' => $recursive ? '' : '/',
337 2
        ])->toArray();
338
    }
339
340
    /**
341
     * @param string $path
342
     *
343
     * @return array|bool
344
     */
345 5
    public function getMetadata($path)
346
    {
347 5
        return $this->client->headObject([
348 5
            'Bucket' => $this->getBucket(),
349 5
            'Key'    => $path,
350 5
        ])->toArray();
351
    }
352
353
    /**
354
     * @param string $path
355
     *
356
     * @return array|bool
357
     */
358 1
    public function getSize($path)
359
    {
360 1
        $meta = $this->getMetadata($path);
361
362
        return isset($meta['ContentLength'])
363
            ? ['size' => $meta['ContentLength']] : false;
364
    }
365
366
    /**
367
     * @param string $path
368
     *
369
     * @return array|bool
370
     */
371 1
    public function getMimetype($path)
372
    {
373 1
        $meta = $this->getMetadata($path);
374
375
        return isset($meta['ContentType'])
376
            ? ['mimetype' => $meta['ContentType']] : false;
377
    }
378
379
    /**
380
     * @param string $path
381
     *
382
     * @return array|bool
383
     */
384 1
    public function getTimestamp($path)
385
    {
386 1
        $meta = $this->getMetadata($path);
387
388
        return isset($meta['LastModified'])
389
            ? ['timestamp' => strtotime($meta['LastModified'])] : false;
390
    }
391
392
    /**
393
     * @param string $path
394
     *
395
     * @return array|bool
396
     */
397 1
    public function getVisibility($path)
398
    {
399 1
        $meta = $this->client->getObjectAcl([
400 1
            'Bucket' => $this->getBucket(),
401 1
            'Key'    => $path,
402 1
        ]);
403
404
        foreach ($meta->get('Grants') as $grant) {
405
            if (isset($grant['Grantee']['URI'])
406
                && $grant['Permission'] === 'READ'
407
                && strpos($grant['Grantee']['URI'], 'global/AllUsers') !== false
408
            ) {
409
                return ['visibility' => AdapterInterface::VISIBILITY_PUBLIC];
410
            }
411
        }
412
413
        return ['visibility' => AdapterInterface::VISIBILITY_PRIVATE];
414
    }
415
}
416