Completed
Push — master ( c52910...66a65c )
by lyu
02:53 queued 47s
created

StreamResponse   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 60
ccs 0
cts 30
cp 0
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
B save() 0 36 9
A saveAs() 0 4 1
1
<?php
2
3
namespace Kaylyu\Alipay\Kernel\Http;
4
5
use Kaylyu\Alipay\Kernel\Exceptions\InvalidArgumentException;
6
use Kaylyu\Alipay\Kernel\Exceptions\RuntimeException;
7
use Kaylyu\Alipay\Support\File;
8
9
/**
10
 * Class StreamResponse.
11
 */
12
class StreamResponse extends Response
13
{
14
    /**
15
     * @param string $directory
16
     * @param string $filename
17
     * @param bool $appendSuffix
18
     * @author kaylv <[email protected]>
19
     * @return string
20
     * @throws InvalidArgumentException
21
     * @throws RuntimeException
22
     */
23
    public function save(string $directory, string $filename = '', bool $appendSuffix = true)
24
    {
25
        $this->getBody()->rewind();
26
27
        $directory = rtrim($directory, '/');
28
29
        if (!is_dir($directory)) {
30
            mkdir($directory, 0755, true); // @codeCoverageIgnore
31
        }
32
33
        if (!is_writable($directory)) {
34
            throw new InvalidArgumentException(sprintf("'%s' is not writable.", $directory));
35
        }
36
37
        $contents = $this->getBody()->getContents();
38
39
        if (empty($contents) || '{' === $contents[0]) {
40
            throw new RuntimeException('Invalid media response content.');
41
        }
42
43
        if (empty($filename)) {
44
            if (preg_match('/filename="(?<filename>.*?)"/', $this->getHeaderLine('Content-Disposition'), $match)) {
45
                $filename = $match['filename'];
46
            } else {
47
                $filename = md5($contents);
48
            }
49
        }
50
51
        if ($appendSuffix && empty(pathinfo($filename, PATHINFO_EXTENSION))) {
52
            $filename .= File::getStreamExt($contents);
53
        }
54
55
        file_put_contents($directory.'/'.$filename, $contents);
56
57
        return $filename;
58
    }
59
60
    /**
61
     * @param string $directory
62
     * @param string $filename
63
     * @param bool $appendSuffix
64
     * @author kaylv <[email protected]>
65
     * @return string
66
     */
67
    public function saveAs(string $directory, string $filename, bool $appendSuffix = true)
68
    {
69
        return $this->save($directory, $filename, $appendSuffix);
70
    }
71
}
72