ReviewOS

also looking at this

meemalabs/meema-client-php

WIP: Upload Endpoint

#38
Merged glennmichael123 wants to merge upload-endpoint into main
6 files +172 -94

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

src/Models/Media.phpmodified+51-6
Changes to src/Models/Media.php
@@ -2,6 +2,9 @@
22
33namespace Meema\MeemaApi\Models;
44
5use GuzzleHttp\Psr7;
6use GuzzleHttp\Psr7\Request;
7use GuzzleHttp\Client as GuzzleClient;
58use Meema\MeemaApi\Client;
69use Meema\MeemaApi\Exceptions\InvalidFormatException;
710use Meema\MeemaApi\Response\Response;
@@ -177,21 +180,63 @@ class Media
177180 public function upload($path)
178181 {
179182 $file = fopen($path, 'r');
183 $stream = Psr7\stream_for($file);
180184
181185 $fileName = basename($path);
182186 $mimeType = mime_content_type($file);
183187
184 $data = ['content_type' => $mimeType];
188 $vaporParams = ['content_type' => $mimeType];
185189
186 $signedUrl = $this->client->request('POST', 'vapor/signed-storage-url', $data);
190 $signedUrl = $this->client->request('POST', 'vapor/signed-storage-url', $vaporParams);
187191
188 return $signedUrl;
192 if (is_array($signedUrl) && $signedUrl['url']) {
193 $headers = $signedUrl['headers'];
194 unset($headers['Host']);
195
196 $this->uploadToS3($signedUrl, $headers, $fileName, $stream);
197
198 $uploadData = ['key' => $signedUrl['key'], 'file_name' => $fileName];
199
200 $response = $this->client->request('POST', 'upload', $uploadData);
201 }
202
203 return $response;
204 }
205
206 /**
207 * Upload the file stream to s3.
208 *
209 * @param array $signedUrl
210 * @param array $headers
211 * @param string $fileName
212 * @param GuzzleHttp\Psr7 $stream
213 *
214 * @return void
215 */
216 protected function uploadToS3($signedUrl, $headers, $fileName, $stream)
217 {
218 $client = new GuzzleClient();
219 $request = new Request(
220 'PUT',
221 $signedUrl['url'],
222 ['headers' => json_encode($headers)],
223 new Psr7\MultipartStream(
224 [
225 [
226 'name' => $fileName,
227 'contents' => $stream,
228 ],
229 ]
230 )
231 );
232
233 $client->send($request);
189234 }
190235
191236 /**
192237 * Archive a media.
193238 *
194 * @param int $ids
239 * @param array $id
195240 *
196241 * @return array
197242 *
@@ -220,7 +265,7 @@ class Media
220265 /**
221266 * Unarchive a media.
222267 *
223 * @param int $id
268 * @param array $id
224269 *
225270 * @return array
226271 *
@@ -249,7 +294,7 @@ class Media
249294 /**
250295 * Make a media private.
251296 *
252 * @param int $id
297 * @param array $id
253298 *
254299 * @return array
255300 *