1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Upyun\Api; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use GuzzleHttp\Psr7; |
7
|
|
|
use Upyun\Config; |
8
|
|
|
use Upyun\Signature; |
9
|
|
|
|
10
|
|
|
class Rest { |
11
|
|
|
/** |
12
|
|
|
* @var Config |
13
|
|
|
*/ |
14
|
|
|
protected $config; |
15
|
|
|
|
16
|
|
|
protected $endpoint; |
17
|
|
|
protected $method; |
18
|
|
|
protected $storagePath; |
19
|
|
|
public $headers = []; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var Psr7\Stream |
23
|
|
|
*/ |
24
|
|
|
protected $file; |
25
|
|
|
|
26
|
|
|
|
27
|
|
|
public function __construct(Config $config) { |
28
|
|
|
$this->config = $config; |
29
|
|
|
$this->endpoint = Config::$restApiEndPoint . '/' . $config->bucketName; |
|
|
|
|
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function request($method, $storagePath) { |
33
|
|
|
$this->method = strtoupper($method); |
34
|
|
|
$this->storagePath = '/' . ltrim($storagePath, '/'); |
35
|
|
|
return $this; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param string|resource $file |
41
|
|
|
* |
42
|
|
|
* @return $this |
43
|
|
|
*/ |
44
|
|
|
public function withFile($file) { |
45
|
|
|
$stream = Psr7\stream_for($file); |
46
|
|
|
$this->file = $stream; |
47
|
|
|
|
48
|
|
|
return $this; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @return mixed|\Psr\Http\Message\ResponseInterface |
53
|
|
|
*/ |
54
|
|
|
public function send() { |
55
|
|
|
$client = new Client([ |
56
|
|
|
'timeout' => $this->config->timeout, |
57
|
|
|
]); |
58
|
|
|
|
59
|
|
|
$url = ($this->config->useSsl ? 'https://' : 'http://') . $this->endpoint . $this->storagePath; |
60
|
|
|
$bodySize = 0; |
61
|
|
|
$body = null; |
62
|
|
|
if($this->file && $this->method === 'PUT') { |
|
|
|
|
63
|
|
|
$bodySize = $this->file->getSize(); |
64
|
|
|
$body = $this->file; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$authHeader = Signature::getRestApiSignHeader($this->config, $this->method, $this->storagePath, $bodySize); |
68
|
|
|
$response = $client->request($this->method, $url, [ |
69
|
|
|
'headers' => array_merge($authHeader, $this->headers), |
70
|
|
|
'body' => $body |
71
|
|
|
]); |
72
|
|
|
|
73
|
|
|
return $response; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
public function withHeader($header, $value) { |
77
|
|
|
$header = strtolower(trim($header)); |
78
|
|
|
|
79
|
|
|
$this->headers[$header] = $value; |
80
|
|
|
return $this; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function withHeaders($headers) { |
84
|
|
|
if(is_array($headers)) { |
|
|
|
|
85
|
|
|
foreach ($headers as $header => $value) { |
86
|
|
|
$this->withHeader($header, $value); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
return $this; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|
This check looks for access to properties that are not accessible from the current context.
If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.