|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the overtrue/wechat. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) overtrue <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* This source file is subject to the MIT license that is bundled |
|
9
|
|
|
* with this source code in the file LICENSE. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace EasyWeChat\Kernel\Http; |
|
13
|
|
|
|
|
14
|
|
|
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException; |
|
15
|
|
|
use EasyWeChat\Kernel\Exceptions\RuntimeException; |
|
16
|
|
|
use EasyWeChat\Kernel\Support\File; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Class StreamResponse. |
|
20
|
|
|
* |
|
21
|
|
|
* @author overtrue <[email protected]> |
|
22
|
|
|
*/ |
|
23
|
|
|
class StreamResponse extends Response |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* @param string $directory |
|
27
|
|
|
* @param string $filename |
|
28
|
|
|
* |
|
29
|
|
|
* @return bool|int |
|
30
|
|
|
* |
|
31
|
|
|
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException |
|
32
|
|
|
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException |
|
33
|
|
|
*/ |
|
34
|
|
|
public function save(string $directory, string $filename = '') |
|
35
|
|
|
{ |
|
36
|
|
|
$this->getBody()->rewind(); |
|
37
|
|
|
|
|
38
|
|
|
$directory = rtrim($directory, '/'); |
|
39
|
|
|
|
|
40
|
|
|
if (!is_dir($directory)) { |
|
41
|
|
|
mkdir($directory, 0755, true); // @codeCoverageIgnore |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (!is_writable($directory)) { |
|
45
|
|
|
throw new InvalidArgumentException(sprintf("'%s' is not writable.", $directory)); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$contents = $this->getBody()->getContents(); |
|
49
|
|
|
|
|
50
|
|
|
if (empty($contents) || $contents[0] == '{') { |
|
51
|
|
|
throw new RuntimeException('Invalid media response content.'); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
if (empty($filename)) { |
|
55
|
|
|
if (preg_match('/filename="(?<filename>.*?)"/', $this->getHeaderLine('Content-Disposition'), $match)) { |
|
56
|
|
|
$filename = $match['filename']; |
|
57
|
|
|
} else { |
|
58
|
|
|
$filename = md5($contents); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
if (empty(pathinfo($filename, PATHINFO_EXTENSION))) { |
|
63
|
|
|
$filename .= File::getStreamExt($contents); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
file_put_contents($directory.'/'.$filename, $contents); |
|
67
|
|
|
|
|
68
|
|
|
return $filename; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param string $directory |
|
73
|
|
|
* @param string $filename |
|
74
|
|
|
* |
|
75
|
|
|
* @return bool|int |
|
76
|
|
|
* |
|
77
|
|
|
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException |
|
78
|
|
|
*/ |
|
79
|
|
|
public function saveAs(string $directory, string $filename) |
|
80
|
|
|
{ |
|
81
|
|
|
return $this->save($directory, $filename); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|