Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/MultipartCopy.php

raw symbols SCIP
1 <?php
2
3 namespace Aws\S3;
4
5 use Aws\Arn\ArnParser;
6 use Aws\Multipart\AbstractUploadManager;
7 use Aws\ResultInterface;
8 use GuzzleHttp\Psr7;
9
10 class MultipartCopy extends AbstractUploadManager
11 {
12 use MultipartUploadingTrait {
13 getInitiateParams as private traitGetInitiateParams;
14 }
15
16 private const VALID_METADATA_DIRECTIVES = [
17 'COPY' => true,
18 'REPLACE' => true,
19 ];
20
21 /**
22 * Metadata fields that can be copied from the source object
23 * to the destination during a multipart copy.
24 */
25 private static array $copyMetadataFields = [
26 'CacheControl',
27 'ContentDisposition',
28 'ContentEncoding',
29 'ContentLanguage',
30 'ContentType',
31 'Expires',
32 'Metadata',
33 ];
34
35 /** @var string|array */
36 private $source;
37 /** @var string */
38 private $sourceVersionId;
39 /** @var ResultInterface */
40 private $sourceMetadata;
41
42 /**
43 * Creates a multipart upload for copying an S3 object.
44 *
45 * The valid configuration options are as follows:
46 *
47 * - acl: (string) ACL to set on the object being upload. Objects are
48 * private by default.
49 * - before_complete: (callable) Callback to invoke before the
50 * `CompleteMultipartUpload` operation. The callback should have a
51 * function signature like `function (Aws\Command $command) {...}`.
52 * - before_initiate: (callable) Callback to invoke before the
53 * `CreateMultipartUpload` operation. The callback should have a function
54 * signature like `function (Aws\Command $command) {...}`.
55 * - before_upload: (callable) Callback to invoke before `UploadPartCopy`
56 * operations. The callback should have a function signature like
57 * `function (Aws\Command $command) {...}`.
58 * - bucket: (string, required) Name of the bucket to which the object is
59 * being uploaded.
60 * - concurrency: (int, default=int(5)) Maximum number of concurrent
61 * `UploadPart` operations allowed during the multipart upload.
62 * - key: (string, required) Key to use for the object being uploaded.
63 * - params: (array) An array of key/value parameters that will be applied
64 * to each of the sub-commands run by the uploader as a base.
65 * Auto-calculated options will override these parameters. If you need
66 * more granularity over parameters to each sub-command, use the before_*
67 * options detailed above to update the commands directly.
68 * - part_size: (int, default=int(5242880)) Part size, in bytes, to use when
69 * doing a multipart upload. This must between 5 MB and 5 GB, inclusive.
70 * - state: (Aws\Multipart\UploadState) An object that represents the state
71 * of the multipart upload and that is used to resume a previous upload.
72 * When this option is provided, the `bucket`, `key`, and `part_size`
73 * options are ignored.
74 * - metadata_directive: (string, default='COPY') Specifies whether to copy
75 * source object metadata to the destination. Set to 'COPY' to
76 * automatically forward metadata fields (Metadata, CacheControl,
77 * ContentDisposition, ContentEncoding, ContentLanguage, ContentType,
78 * Expires) from the source object. When set to 'COPY', source metadata
79 * takes precedence and any matching fields provided in 'params' are
80 * ignored. Set to 'REPLACE' to suppress automatic metadata copying and
81 * use your own values via the 'params' option.
82 * - source_metadata: (Aws\ResultInterface) The result of a HeadObject call
83 * on the copy source. If not provided, the SDK makes a HeadObject request
84 * to obtain the source object's size and metadata. Providing this avoids
85 * the extra request.
86 * - display_progress: (boolean) Set true to track status in 1/8th increments
87 * for upload.
88 *
89 * @param S3ClientInterface $client Client used for the upload.
90 * @param string|array $source Location of the data to be copied (in the
91 * form /<bucket>/<key>). If the key contains a '?'
92 * character, instead pass an array of source_key,
93 * source_bucket, and source_version_id.
94 * @param array $config Configuration used to perform the upload.
95 */
96 public function __construct(
97 S3ClientInterface $client,
98 $source,
99 array $config = []
100 ) {
101 if (is_array($source)) {
102 $this->source = $source;
103 } else {
104 $this->source = $this->getInputSource($source);
105 }
106
107 parent::__construct(
108 $client,
109 array_change_key_case($config) + ['source_metadata' => null]
110 );
111
112 if ($this->displayProgress) {
113 $this->getState()->setProgressThresholds(
114 $this->sourceMetadata["ContentLength"]
115 );
116 }
117 }
118
119 /**
120 * An alias of the self::upload method.
121 *
122 * @see self::upload
123 */
124 public function copy()
125 {
126 return $this->upload();
127 }
128
129 protected function loadUploadWorkflowInfo()
130 {
131 return [
132 'command' => [
133 'initiate' => 'CreateMultipartUpload',
134 'upload' => 'UploadPartCopy',
135 'complete' => 'CompleteMultipartUpload',
136 ],
137 'id' => [
138 'bucket' => 'Bucket',
139 'key' => 'Key',
140 'upload_id' => 'UploadId',
141 ],
142 'part_num' => 'PartNumber',
143 ];
144 }
145
146 protected function getUploadCommands(callable $resultHandler)
147 {
148 $parts = ceil($this->getSourceSize() / $this->determinePartSize());
149
150 for ($partNumber = 1; $partNumber <= $parts; $partNumber++) {
151 // If we haven't already uploaded this part, yield a new part.
152 if (!$this->state->hasPartBeenUploaded($partNumber)) {
153 $command = $this->client->getCommand(
154 $this->info['command']['upload'],
155 $this->createPart($partNumber, $parts) + $this->getState()->getId()
156 );
157 $command->getHandlerList()->appendSign($resultHandler, 'mup');
158 yield $command;
159 }
160 }
161 }
162
163 private function createPart($partNumber, $partsCount)
164 {
165 $data = [];
166
167 // Apply custom params to UploadPartCopy data
168 $config = $this->getConfig();
169 $params = isset($config['params']) ? $config['params'] : [];
170 foreach ($params as $k => $v) {
171 $data[$k] = $v;
172 }
173 // The source parameter here is usually a string, but can be overloaded as an array
174 // if the key contains a '?' character to specify where the query parameters start
175 if (is_array($this->source)) {
176 $key = str_replace('%2F', '/', rawurlencode($this->source['source_key']));
177 $bucket = $this->source['source_bucket'];
178 } else {
179 list($bucket, $key) = explode('/', ltrim($this->source, '/'), 2);
180 $key = implode(
181 '/',
182 array_map(
183 'urlencode',
184 explode('/', rawurldecode($key))
185 )
186 );
187 }
188
189 $uri = ArnParser::isArn($bucket) ? '' : '/';
190 $uri .= $bucket . '/' . $key;
191 $data['CopySource'] = $uri;
192 $data['PartNumber'] = $partNumber;
193 if (!empty($this->sourceVersionId)) {
194 $data['CopySource'] .= "?versionId=" . $this->sourceVersionId;
195 }
196
197 $defaultPartSize = $this->determinePartSize();
198 $startByte = $defaultPartSize * ($partNumber - 1);
199 $data['ContentLength'] = $partNumber < $partsCount
200 ? $defaultPartSize
201 : $this->getSourceSize() - ($defaultPartSize * ($partsCount - 1));
202 $endByte = $startByte + $data['ContentLength'] - 1;
203 $data['CopySourceRange'] = "bytes=$startByte-$endByte";
204
205 return $data;
206 }
207
208 protected function extractETag(ResultInterface $result)
209 {
210 return $result->search('CopyPartResult.ETag');
211 }
212
213 protected function getInitiateParams()
214 {
215 $params = $this->traitGetInitiateParams();
216
217 $directive = strtoupper($this->config['metadata_directive'] ?? 'COPY');
218
219 if (!isset(self::VALID_METADATA_DIRECTIVES[$directive])) {
220 throw new \InvalidArgumentException(
221 "Invalid metadata_directive value '$directive'."
222 . " Must be 'COPY' or 'REPLACE'."
223 );
224 }
225
226 if ($directive === 'COPY') {
227 $sourceMetadata = $this->getSourceMetadata();
228 foreach (self::$copyMetadataFields as $field) {
229 if (!empty($sourceMetadata[$field])) {
230 $params[$field] = $sourceMetadata[$field];
231 }
232 }
233 }
234
235 return $params;
236 }
237
238 protected function getSourceMimeType()
239 {
240 return $this->getSourceMetadata()['ContentType'];
241 }
242
243 protected function getSourceSize()
244 {
245 return $this->getSourceMetadata()['ContentLength'];
246 }
247
248 private function getSourceMetadata()
249 {
250 if (empty($this->sourceMetadata)) {
251 $this->sourceMetadata = $this->fetchSourceMetadata();
252 }
253
254 return $this->sourceMetadata;
255 }
256
257 private function fetchSourceMetadata()
258 {
259 if ($this->config['source_metadata'] instanceof ResultInterface) {
260 return $this->config['source_metadata'];
261 }
262 //if the source variable was overloaded with an array, use the inputs for key and bucket
263 if (is_array($this->source)) {
264 $headParams = [
265 'Key' => $this->source['source_key'],
266 'Bucket' => $this->source['source_bucket']
267 ];
268 if (isset($this->source['source_version_id'])) {
269 $this->sourceVersionId = $this->source['source_version_id'];
270 $headParams['VersionId'] = $this->sourceVersionId;
271 }
272 //otherwise, use the default source parsing behavior
273 } else {
274 list($bucket, $key) = explode('/', ltrim($this->source, '/'), 2);
275 $headParams = [
276 'Bucket' => $bucket,
277 'Key' => $key,
278 ];
279 if (strpos($key, '?')) {
280 list($key, $query) = explode('?', $key, 2);
281 $headParams['Key'] = $key;
282 $query = Psr7\Query::parse($query, false);
283 if (isset($query['versionId'])) {
284 $this->sourceVersionId = $query['versionId'];
285 $headParams['VersionId'] = $this->sourceVersionId;
286 }
287 }
288 }
289 return $this->client->headObject($headParams);
290 }
291
292 /**
293 * Get the url decoded input source, starting with a slash if it is not an
294 * ARN to standardize the source location syntax.
295 *
296 * @param string $inputSource The source that was passed to the constructor
297 * @return string The source, starting with a slash if it's not an arn
298 */
299 private function getInputSource($inputSource)
300 {
301 $sourceBuilder = ArnParser::isArn($inputSource) ? '' : '/';
302 $sourceBuilder .= ltrim(rawurldecode($inputSource), '/');
303 return $sourceBuilder;
304 }
305 }