1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ArgentCrusade\Selectel\CloudStorage; |
4
|
|
|
|
5
|
|
|
use ArgentCrusade\Selectel\CloudStorage\Contracts\Api\ApiClientContract; |
6
|
|
|
use ArgentCrusade\Selectel\CloudStorage\Contracts\FileUploaderContract; |
7
|
|
|
use ArgentCrusade\Selectel\CloudStorage\Exceptions\UploadFailedException; |
8
|
|
|
|
9
|
|
|
class FileUploader implements FileUploaderContract |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Upload file from string or stream resource. |
13
|
|
|
* |
14
|
|
|
* @param \ArgentCrusade\Selectel\CloudStorage\Contracts\Api\ApiClientContract $api |
15
|
|
|
* @param string $path Remote path. |
16
|
|
|
* @param string|resource $body File contents. |
17
|
|
|
* @param array $params = [] Upload params. |
18
|
|
|
* @param bool $verifyChecksum = true |
19
|
|
|
* |
20
|
|
|
* @throws \ArgentCrusade\Selectel\CloudStorage\Exceptions\UploadFailedException |
21
|
|
|
* |
22
|
|
|
* @return string |
23
|
|
|
*/ |
24
|
|
|
public function upload(ApiClientContract $api, $path, $body, array $params = [], $verifyChecksum = true) |
25
|
|
|
{ |
26
|
|
|
$response = $api->request('PUT', $path, [ |
27
|
|
|
'headers' => $this->convertUploadParamsToHeaders($body, $params, $verifyChecksum), |
|
|
|
|
28
|
|
|
'body' => $body, |
29
|
|
|
]); |
30
|
|
|
|
31
|
|
|
if ($response->getStatusCode() !== 201) { |
32
|
|
|
throw new UploadFailedException('Unable to upload file.', $response->getStatusCode()); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return $response->getHeaderLine('ETag'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Parses upload parameters and assigns them to appropriate HTTP headers. |
40
|
|
|
* |
41
|
|
|
* @param string $body = null |
42
|
|
|
* @param array $params = [] |
43
|
|
|
* @param bool $verifyChecksum = true |
44
|
|
|
* |
45
|
|
|
* @return array |
46
|
|
|
*/ |
47
|
|
|
protected function convertUploadParamsToHeaders($body = null, array $params = [], $verifyChecksum = true) |
48
|
|
|
{ |
49
|
|
|
$headers = []; |
50
|
|
|
|
51
|
|
|
if ($verifyChecksum) { |
52
|
|
|
$headers['ETag'] = md5($body); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$availableParams = [ |
56
|
|
|
'contentType' => 'Content-Type', |
57
|
|
|
'contentDisposition' => 'Content-Disposition', |
58
|
|
|
'deleteAfter' => 'X-Delete-After', |
59
|
|
|
'deleteAt' => 'X-Delete-At', |
60
|
|
|
]; |
61
|
|
|
|
62
|
|
|
foreach ($availableParams as $key => $header) { |
63
|
|
|
if (isset($params[$key])) { |
64
|
|
|
$headers[$header] = $params[$key]; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $headers; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
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.