Skip to content

Commit 02fb57c

Browse files
authored
Merge pull request #8 from BrightLocal/feature/upload-files
Added the ability to upload files
2 parents 88d8d83 + 8fce25e commit 02fb57c

File tree

1 file changed

+36
-8
lines changed

1 file changed

+36
-8
lines changed

src/BrightLocal/Api.php

+36-8
Original file line numberDiff line numberDiff line change
@@ -63,26 +63,22 @@ public function get_sig_and_expires() {
6363
* @throws \Exception
6464
* @return bool|mixed
6565
*/
66-
public function call($method, $params = array(), $httpMethod = self::HTTP_METHOD_POST) {
66+
public function call($method, $params = [], $httpMethod = self::HTTP_METHOD_POST) {
6767
if (!in_array($httpMethod, $this->allowedHttpMethods)) {
6868
throw new \Exception('Invalid HTTP method specified.');
6969
}
7070
$method = str_replace('/seo-tools/api', '', $method);
7171
// some methods only require api key but there's no harm in also sending
7272
// sig and expires to those methods
7373
list($sig, $expires) = $this->get_sig_and_expires();
74-
$params = array_merge(array(
74+
$params = array_merge([
7575
'api-key' => $this->apiKey,
7676
'sig' => $sig,
7777
'expires' => $expires
78-
), $params);
78+
], $params);
7979
$client = new Client;
8080
try {
81-
if ($httpMethod === static::HTTP_METHOD_GET) {
82-
$result = $client->get($this->endpoint . '/' . ltrim($method, '/'), array('query' => $params));
83-
} else {
84-
$result = $client->$httpMethod($this->endpoint . '/' . ltrim($method, '/'), array('form_params' => $params));
85-
}
81+
$result = $client->$httpMethod($this->endpoint . '/' . ltrim($method, '/'), $this->get_options($httpMethod, $params));
8682
} catch (RequestException $e) {
8783
$result = $e->getResponse();
8884
}
@@ -134,4 +130,36 @@ public function delete($method, $params = array()) {
134130
public function get_last_http_code() {
135131
return $this->lastHttpCode;
136132
}
133+
134+
/**
135+
* @param $httpMethod
136+
* @param array $params
137+
* @return array
138+
*/
139+
private function get_options($httpMethod, $params) {
140+
if ($httpMethod === static::HTTP_METHOD_GET) {
141+
return ['query' => $params];
142+
}
143+
foreach ($params as $param) {
144+
if (is_resource($param)) {
145+
return ['multipart' => $this->convert_to_multipart($params)];
146+
}
147+
}
148+
return ['form_params' => $params];
149+
}
150+
151+
/**
152+
* @param array $params
153+
* @return array
154+
*/
155+
private function convert_to_multipart($params) {
156+
$multipart = [];
157+
foreach ($params as $key => $value) {
158+
$multipart[] = [
159+
'name' => $key,
160+
'contents' => $value,
161+
];
162+
}
163+
return $multipart;
164+
}
137165
}

0 commit comments

Comments
 (0)