Passed
Push — master ( d7de4b...3cd345 )
by alpha
07:46
created

AliyunOssAdapter::readStream()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 6
cp 0
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Created by jacob.
4
 * Date: 2016/5/19 0019
5
 * Time: 下午 17:07
6
 */
7
8
namespace AlphaSnow\AliyunOss;
9
10
use Carbon\Carbon;
11
use League\Flysystem\Adapter\AbstractAdapter;
12
use League\Flysystem\AdapterInterface;
13
use League\Flysystem\Config;
14
use League\Flysystem\Util;
15
use League\Flysystem\FileNotFoundException;
16
use OSS\Core\OssException;
17
use OSS\OssClient;
18
use Illuminate\Support\Facades\Log;
19
20
class AliyunOssAdapter extends AbstractAdapter
21
{
22
    /**
23
     * @var bool
24
     */
25
    protected $debug;
26
    /**
27
     * @var array
28
     */
29
    protected static $resultMap = [
30
        'Body' => 'raw_contents',
31
        'Content-Length' => 'size',
32
        'ContentType' => 'mimetype',
33
        'Size' => 'size',
34
        'StorageClass' => 'storage_class',
35
    ];
36
    /**
37
     * @var array
38
     */
39
    protected static $metaOptions = [
40
        'CacheControl',
41
        'Expires',
42
        'ServerSideEncryption',
43
        'Metadata',
44
        'ACL',
45
        'ContentType',
46
        'ContentDisposition',
47
        'ContentLanguage',
48
        'ContentEncoding',
49
    ];
50
51
    /**
52
     * @var string[]
53
     */
54
    protected static $metaMap = [
55
        'CacheControl' => 'Cache-Control',
56
        'Expires' => 'Expires',
57
        'ServerSideEncryption' => 'x-oss-server-side-encryption',
58
        'Metadata' => 'x-oss-metadata-directive',
59
        'ACL' => 'x-oss-object-acl',
60
        'ContentType' => 'Content-Type',
61
        'ContentDisposition' => 'Content-Disposition',
62
        'ContentLanguage' => 'response-content-language',
63
        'ContentEncoding' => 'Content-Encoding',
64
    ];
65
66
    /**
67
     * @var OssClient
68
     */
69
    protected $client;
70
    /**
71
     * @var string
72
     */
73
    protected $bucket;
74
    /**
75
     * @var string
76
     */
77
    protected $endPoint;
78
79
    /**
80
     * @var string
81
     */
82
    protected $cdnDomain;
83
84
    /**
85
     * @var bool
86
     */
87
    protected $ssl;
88
89
    /**
90
     * @var bool
91
     */
92
    protected $isCname;
93
94
    /**
95
     * @var array|int[]
96
     */
97
    protected $options = [
98
        'Multipart' => 128
99
    ];
100
101
    /**
102
     * AliyunOssAdapter constructor.
103
     * @param OssClient $client
104
     * @param AliyunOssConfig $config
105
     * @param array $options
106
     */
107 1
    public function __construct(
108
        OssClient $client,
109
        AliyunOssConfig $config,
110
        array $options = []
111
    ) {
112 1
        $this->client = $client;
113 1
        $this->debug = $config->isDebug();
114 1
        $this->bucket = $config->getBucket();
115 1
        $this->endPoint = $config->getEndpoint();
116 1
        $this->ssl = $config->isSsl();
117 1
        $this->isCname = $config->isCname();
118 1
        $this->cdnDomain = $config->getCdnDomain();
119 1
        $this->options = array_merge($this->options, $options);
120 1
    }
121
122
    /**
123
     * Get the OssClient bucket.
124
     *
125
     * @return string
126
     */
127
    public function getBucket()
128
    {
129
        return $this->bucket;
130
    }
131
132
    /**
133
     * Get the OSSClient instance.
134
     *
135
     * @return OssClient
136
     */
137
    public function getClient()
138
    {
139
        return $this->client;
140
    }
141
142
    /**
143
     * @param OssClient $client
144
     * @return $this
145
     */
146
    public function setClient(OssClient $client)
147
    {
148
        $this->client = $client;
149
        return $this;
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155 3
    public function write($path, $contents, Config $config)
156
    {
157 3
        $object = $this->applyPathPrefix($path);
158 3
        $options = $this->getOptions($this->options, $config);
159
160 3
        if (!isset($options[OssClient::OSS_LENGTH])) {
161 3
            $options[OssClient::OSS_LENGTH] = Util::contentSize($contents);
162
        }
163 3 View Code Duplication
        if (!isset($options[OssClient::OSS_CONTENT_TYPE])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164 3
            $options[OssClient::OSS_CONTENT_TYPE] = Util::guessMimeType($path, $contents);
165
        }
166
        try {
167 3
            $this->client->putObject($this->bucket, $object, $contents, $options);
168
        } catch (OssException $e) {
169
            $this->logErr(__FUNCTION__, $e);
170
            return false;
171
        }
172 3
        return $this->normalizeResponse($options, $path);
173
    }
174
175
    /**
176
     * {@inheritdoc}
177
     */
178 1
    public function writeStream($path, $resource, Config $config)
179
    {
180 1
        $options = $this->getOptions($this->options, $config);
0 ignored issues
show
Unused Code introduced by
$options 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...
181 1
        $contents = stream_get_contents($resource);
182
183 1
        return $this->write($path, $contents, $config);
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189 1
    public function writeFile($path, $filePath, Config $config)
190
    {
191 1
        $object = $this->applyPathPrefix($path);
192 1
        $options = $this->getOptions($this->options, $config);
193
194 1
        $options[OssClient::OSS_CHECK_MD5] = true;
195
196 1 View Code Duplication
        if (!isset($options[OssClient::OSS_CONTENT_TYPE])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
197 1
            $options[OssClient::OSS_CONTENT_TYPE] = Util::guessMimeType($path, '');
198
        }
199
        try {
200 1
            $this->client->uploadFile($this->bucket, $object, $filePath, $options);
201
        } catch (OssException $e) {
202
            $this->logErr(__FUNCTION__, $e);
203
            return false;
204
        }
205 1
        return $this->normalizeResponse($options, $path);
206
    }
207
208
    /**
209
     * {@inheritdoc}
210
     */
211
    public function update($path, $contents, Config $config)
212
    {
213
        if (!$config->has('visibility') && !$config->has('ACL')) {
214
            $config->set(static::$metaMap['ACL'], $this->getObjectACL($path));
215
        }
216
        // $this->delete($path);
217
        return $this->write($path, $contents, $config);
218
    }
219
220
    /**
221
     * {@inheritdoc}
222
     */
223
    public function updateStream($path, $resource, Config $config)
224
    {
225
        $contents = stream_get_contents($resource);
226
        return $this->update($path, $contents, $config);
227
    }
228
229
    /**
230
     * {@inheritdoc}
231
     */
232
    public function rename($path, $newpath)
233
    {
234
        if (!$this->copy($path, $newpath)) {
235
            return false;
236
        }
237
238
        return $this->delete($path);
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 View Code Duplication
    public function copy($path, $newpath)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
    {
246
        $object = $this->applyPathPrefix($path);
247
        $newObject = $this->applyPathPrefix($newpath);
248
        try {
249
            $this->client->copyObject($this->bucket, $object, $this->bucket, $newObject);
250
        } catch (OssException $e) {
251
            $this->logErr(__FUNCTION__, $e);
252
            return false;
253
        }
254
255
        return true;
256
    }
257
258
    /**
259
     * {@inheritdoc}
260
     */
261 View Code Duplication
    public function delete($path)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
262
    {
263
        $bucket = $this->bucket;
264
        $object = $this->applyPathPrefix($path);
265
266
        try {
267
            $this->client->deleteObject($bucket, $object);
268
        } catch (OssException $e) {
269
            $this->logErr(__FUNCTION__, $e);
270
            return false;
271
        }
272
273
        return !$this->has($path);
274
    }
275
276
    /**
277
     * {@inheritdoc}
278
     */
279
    public function deleteDir($dirname)
280
    {
281
        $dirname = rtrim($this->applyPathPrefix($dirname), '/') . '/';
282
        $dirObjects = $this->listDirObjects($dirname, true);
283
284
        if (count($dirObjects['objects']) > 0) {
285
            $objects = [];
286
            foreach ($dirObjects['objects'] as $object) {
287
                $objects[] = $object['Key'];
288
            }
289
290
            try {
291
                $this->client->deleteObjects($this->bucket, $objects);
292
            } catch (OssException $e) {
293
                $this->logErr(__FUNCTION__, $e);
294
                return false;
295
            }
296
        }
297
298
        try {
299
            $this->client->deleteObject($this->bucket, $dirname);
300
        } catch (OssException $e) {
301
            $this->logErr(__FUNCTION__, $e);
302
            return false;
303
        }
304
305
        return true;
306
    }
307
308
    /**
309
     * {@inheritdoc}
310
     */
311
    public function createDir($dirname, Config $config)
312
    {
313
        $object = $this->applyPathPrefix($dirname);
314
        $options = $this->getOptionsFromConfig($config);
315
316
        try {
317
            $this->client->createObjectDir($this->bucket, $object, $options);
318
        } catch (OssException $e) {
319
            $this->logErr(__FUNCTION__, $e);
320
            return false;
321
        }
322
323
        return ['path' => $dirname, 'type' => 'dir'];
324
    }
325
326
    /**
327
     * {@inheritdoc}
328
     */
329
    public function setVisibility($path, $visibility)
330
    {
331
        $object = $this->applyPathPrefix($path);
332
        $acl = ($visibility === AdapterInterface::VISIBILITY_PUBLIC) ? OssClient::OSS_ACL_TYPE_PUBLIC_READ : OssClient::OSS_ACL_TYPE_PRIVATE;
333
334
        $this->client->putObjectAcl($this->bucket, $object, $acl);
335
336
        return compact('visibility');
337
    }
338
339
    /**
340
     * 列举文件夹内文件列表;可递归获取子文件夹;
341
     * @param string $dirname 目录
342
     * @param bool $recursive 是否递归
343
     * @return mixed
344
     * @throws OssException
345
     */
346
    public function listDirObjects($dirname = '', $recursive = false)
347
    {
348
        $delimiter = '/';
349
        $nextMarker = '';
350
        $maxkeys = 1000;
351
352
        //存储结果
353
        $result = [];
354
355
        while (true) {
356
            $options = [
357
                'delimiter' => $delimiter,
358
                'prefix' => $dirname,
359
                'max-keys' => $maxkeys,
360
                'marker' => $nextMarker,
361
            ];
362
363
            try {
364
                $listObjectInfo = $this->client->listObjects($this->bucket, $options);
365
            } catch (OssException $e) {
366
                $this->logErr(__FUNCTION__, $e);
367
                // return false;
368
                throw $e;
369
            }
370
371
            $nextMarker = $listObjectInfo->getNextMarker(); // 得到nextMarker,从上一次listObjects读到的最后一个文件的下一个文件开始继续获取文件列表
372
            $objectList = $listObjectInfo->getObjectList(); // 文件列表
373
            $prefixList = $listObjectInfo->getPrefixList(); // 目录列表
374
375
            if (!empty($objectList)) {
376
                foreach ($objectList as $objectInfo) {
377
                    $object['Prefix'] = $dirname;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$object was never initialized. Although not strictly required by PHP, it is generally a good practice to add $object = 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...
378
                    $object['Key'] = $objectInfo->getKey();
0 ignored issues
show
Bug introduced by
The variable $object 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...
379
                    $object['LastModified'] = $objectInfo->getLastModified();
380
                    $object['eTag'] = $objectInfo->getETag();
381
                    $object['Type'] = $objectInfo->getType();
382
                    $object['Size'] = $objectInfo->getSize();
383
                    $object['StorageClass'] = $objectInfo->getStorageClass();
384
385
                    $result['objects'][] = $object;
386
                }
387
            } else {
388
                $result["objects"] = [];
389
            }
390
391
            if (!empty($prefixList)) {
392
                foreach ($prefixList as $prefixInfo) {
393
                    $result['prefix'][] = $prefixInfo->getPrefix();
394
                }
395
            } else {
396
                $result['prefix'] = [];
397
            }
398
399
            //递归查询子目录所有文件
400
            if ($recursive) {
401
                foreach ($result['prefix'] as $pfix) {
402
                    $next = $this->listDirObjects($pfix, $recursive);
403
                    $result["objects"] = array_merge($result['objects'], $next["objects"]);
404
                }
405
            }
406
407
            //没有更多结果了
408
            if ($nextMarker === '') {
409
                break;
410
            }
411
        }
412
413
        return $result;
414
    }
415
416
    /**
417
     * {@inheritdoc}
418
     */
419 1
    public function has($path)
420
    {
421 1
        $object = $this->applyPathPrefix($path);
422
423 1
        return $this->client->doesObjectExist($this->bucket, $object);
424
    }
425
426
    /**
427
     * {@inheritdoc}
428
     */
429
    public function read($path)
430
    {
431
        $result = $this->readObject($path);
432
        $result['contents'] = (string)$result['raw_contents'];
433
        unset($result['raw_contents']);
434
        return $result;
435
    }
436
437
    /**
438
     * {@inheritdoc}
439
     */
440
    public function readStream($path)
441
    {
442
        $result = $this->readObject($path);
443
        $result['stream'] = $result['raw_contents'];
444
        rewind($result['stream']);
445
        // Ensure the EntityBody object destruction doesn't close the stream
446
        // $result['raw_contents']->detachStream();
447
        unset($result['raw_contents']);
448
449
        return $result;
450
    }
451
452
    /**
453
     * {@inheritdoc}
454
     */
455
    public function listContents($directory = '', $recursive = false)
456
    {
457
        $dirObjects = $this->listDirObjects($directory, true);
458
        $contents = $dirObjects["objects"];
459
460
        $result = array_map([$this, 'normalizeResponse'], $contents);
461
        $result = array_filter($result, function ($value) {
462
            return $value['path'] !== false;
463
        });
464
465
        return Util::emulateDirectories($result);
466
    }
467
468
    /**
469
     * {@inheritdoc}
470
     */
471 View Code Duplication
    public function getMetadata($path)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
472
    {
473
        $object = $this->applyPathPrefix($path);
474
475
        try {
476
            $objectMeta = $this->client->getObjectMeta($this->bucket, $object);
477
        } catch (OssException $e) {
478
            $this->logErr(__FUNCTION__, $e);
479
            return false;
480
        }
481
482
        return $objectMeta;
483
    }
484
485
    /**
486
     * {@inheritdoc}
487
     */
488
    public function getSize($path)
489
    {
490
        $object = $this->getMetadata($path);
491
        $object['size'] = $object['content-length'];
492
        return $object;
493
    }
494
495
    /**
496
     * {@inheritdoc}
497
     */
498
    public function getMimetype($path)
499
    {
500
        if ($object = $this->getMetadata($path)) {
501
            $object['mimetype'] = $object['content-type'];
502
        }
503
        return $object;
504
    }
505
506
    /**
507
     * {@inheritdoc}
508
     */
509
    public function getTimestamp($path)
510
    {
511
        if ($object = $this->getMetadata($path)) {
512
            $object['timestamp'] = strtotime($object['last-modified']);
513
        }
514
        return $object;
515
    }
516
517
    /**
518
     * {@inheritdoc}
519
     */
520
    public function getVisibility($path)
521
    {
522
        $object = $this->applyPathPrefix($path);
523
        try {
524
            $acl = $this->client->getObjectAcl($this->bucket, $object);
525
        } catch (OssException $e) {
526
            $this->logErr(__FUNCTION__, $e);
527
            return false;
528
        }
529
530
        if ($acl == OssClient::OSS_ACL_TYPE_PUBLIC_READ) {
531
            $res['visibility'] = AdapterInterface::VISIBILITY_PUBLIC;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$res was never initialized. Although not strictly required by PHP, it is generally a good practice to add $res = 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...
532
        } else {
533
            $res['visibility'] = AdapterInterface::VISIBILITY_PRIVATE;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$res was never initialized. Although not strictly required by PHP, it is generally a good practice to add $res = 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...
534
        }
535
536
        return $res;
537
    }
538
539
    /**
540
     * @param string $path
541
     * @return array|null[]|string[]
542
     */
543
    protected function readObject($path)
544
    {
545
        $object = $this->applyPathPrefix($path);
546
        $result = [];
547
        $result['Body'] = $this->client->getObject($this->bucket, $object);
548
        $result = array_merge($result, ['type' => 'file']);
549
        return $this->normalizeResponse($result, $path);
550
    }
551
552
    /**
553
     * @param string $path
554
     * @return string
555
     */
556
    public function getUrl($path)
557
    {
558
        // if (!$this->has($path)) throw new FileNotFoundException($path.' not found');
559
        return ($this->ssl ? 'https://' : 'http://') . ($this->isCname ? ($this->cdnDomain == '' ? $this->endPoint : $this->cdnDomain) : $this->bucket . '.' . $this->endPoint) . '/' . ltrim($path, '/');
560
    }
561
562
    /**
563
     * Get a temporary URL for the file at the given path.
564
     *
565
     * @param string $path
566
     * @param \DateTimeInterface|int $expiration
567
     * @param array $options
568
     * @return string
569
     *
570
     * @throws \RuntimeException
571
     */
572
    public function getTemporaryUrl($path, $expiration, array $options = [])
573
    {
574
        if ($expiration instanceof Carbon) {
575
            return $this->client->generatePresignedUrl($this->bucket, $path, $expiration->getTimestamp(), $options);
0 ignored issues
show
Documentation introduced by
$options is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
576
        }
577
        return $this->client->signUrl($this->bucket, $path, $expiration, $options);
0 ignored issues
show
Bug introduced by
It seems like $expiration defined by parameter $expiration on line 572 can also be of type object<DateTimeInterface>; however, OSS\OssClient::signUrl() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Documentation introduced by
$options is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
578
    }
579
580
    /**
581
     * The the ACL visibility.
582
     *
583
     * @param string $path
584
     *
585
     * @return string
586
     */
587
    protected function getObjectACL($path)
588
    {
589
        $metadata = $this->getVisibility($path);
590
591
        return $metadata['visibility'] === AdapterInterface::VISIBILITY_PUBLIC ? OssClient::OSS_ACL_TYPE_PUBLIC_READ : OssClient::OSS_ACL_TYPE_PRIVATE;
592
    }
593
594
    /**
595
     * Normalize a result from OSS.
596
     *
597
     * @param array $object
598
     * @param string $path
599
     *
600
     * @return array file metadata
601
     */
602 4
    protected function normalizeResponse(array $object, $path = null)
603
    {
604 4
        $result = ['path' => $path ?: $this->removePathPrefix(isset($object['Key']) ? $object['Key'] : $object['Prefix'])];
605 4
        $result['dirname'] = Util::dirname($result['path']);
606
607 4
        if (isset($object['LastModified'])) {
608
            $result['timestamp'] = strtotime($object['LastModified']);
609
        }
610
611 4
        if (substr($result['path'], -1) === '/') {
612
            $result['type'] = 'dir';
613
            $result['path'] = rtrim($result['path'], '/');
614
615
            return $result;
616
        }
617
618 4
        $result = array_merge($result, Util::map($object, static::$resultMap), ['type' => 'file']);
619
620 4
        return $result;
621
    }
622
623
    /**
624
     * Get options for a OSS call. done
625
     *
626
     * @param array $options
627
     *
628
     * @return array OSS options
629
     */
630 4
    protected function getOptions(array $options = [], Config $config = null)
631
    {
632 4
        $options = array_merge($this->options, $options);
633
634 4
        if ($config) {
635 4
            $options = array_merge($options, $this->getOptionsFromConfig($config));
636
        }
637
638 4
        return array(OssClient::OSS_HEADERS => $options);
639
    }
640
641
    /**
642
     * Retrieve options from a Config instance. done
643
     *
644
     * @param Config $config
645
     *
646
     * @return array
647
     */
648 4
    protected function getOptionsFromConfig(Config $config)
649
    {
650 4
        $options = [];
651
652 4
        foreach (static::$metaOptions as $option) {
653 4
            if (!$config->has($option)) {
654 4
                continue;
655
            }
656
            $options[static::$metaMap[$option]] = $config->get($option);
657
        }
658
659 4
        if ($visibility = $config->get('visibility')) {
660
            // For local reference
661
            // $options['visibility'] = $visibility;
662
            // For external reference
663
            $options['x-oss-object-acl'] = $visibility === AdapterInterface::VISIBILITY_PUBLIC ? OssClient::OSS_ACL_TYPE_PUBLIC_READ : OssClient::OSS_ACL_TYPE_PRIVATE;
664
        }
665
666 4
        if ($mimetype = $config->get('mimetype')) {
667
            // For local reference
668
            // $options['mimetype'] = $mimetype;
669
            // For external reference
670
            $options['Content-Type'] = $mimetype;
671
        }
672
673 4
        return $options;
674
    }
675
676
    /**
677
     * @param string $func
678
     * @param \Exception $e
679
     */
680
    protected function logErr($func, $e)
681
    {
682
        if ($this->debug) {
683
            Log::error($func . ": FAILED");
684
            Log::error($e->getMessage());
685
        }
686
    }
687
}
688