Commit 04f76205 authored by Dmitry Nikulin's avatar Dmitry Nikulin

Switch to Guzzle for HTTP requests

parent 3896f960
composer.lock
vendor
......@@ -5,5 +5,8 @@
"psr-4": {
"AttachmentsClient\\": "src/"
}
},
"require": {
"guzzlehttp/guzzle": "^6.3"
}
}
\ No newline at end of file
}
<?php
namespace AttachmentsClient;
require('vendor/autoload.php');
use GuzzleHttp\Client;
class AttachmentsClient {
private $baseUrl;
private $client;
function __construct ($baseUrl) {
$this->baseUrl = $this->ensureNotEndsWithSlash($baseUrl);
$this->client = new Client();
}
// *** Public API methods ***
/**
* Uploads a file to attachments server.
* Uploads a file from filesystem to attachments server.
*
* @param string $filename Path to file to be uploaded
*
* @return string Hash of uploaded file
*/
public function uploadFromFile ($filename) {
$data = new \CurlFile($filename);
return $this->uploadFromMemory($data);
$data = file_get_contents($filename);
return $this->uploadFromMemory($data, basename($filename));
}
/**
* Uploads data from memory to attachments server.
*
* @param string $file File data to be uploaded, stored in memory
* @param string $name (optional) Name of file to be passed to server
*
* @return string Hash of uploaded file
*/
public function uploadFromMemory ($data) {
public function uploadFromMemory ($data, $name = 'file') {
$url = $this->getFullMethodUrl('/ul');
$result = $this->sendPostRequest($url, $data);
$result = $this->sendPostRequestWithFile ($url, $data, $name);
$json = json_decode($result, true);
return $json['id'];
......@@ -48,22 +55,29 @@ class AttachmentsClient {
return $this->baseUrl . $method;
}
private function sendPostRequest ($url, $data) {
$fields = array(
'file' => $data
);
private function sendPostRequestWithFile ($url, $file, $name) {
$response = $this->client->request('POST', $url, [
'multipart' => [
[
'name' => 'file',
'contents' => $file,
'filename' => $name
]
]
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo $response->getBody();
$result = curl_exec($ch);
curl_close($ch);
if ($response->getStatusCode() !== 200) {
$message =
'File uploading failed: server returned ' .
$response->getStatusCode() .
' and body: ' .
$response->getBody();
throw new Exception($message);
}
return $result;
return $response->getBody();
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment