Skip to content

Commit a2cbf6d

Browse files
committed
Merge pull request #21 from uzairfarooq/http_error_codes_handling
If there's an http error code, return the error in all results
2 parents 461886c + adceac0 commit a2cbf6d

1 file changed

Lines changed: 31 additions & 4 deletions

File tree

src/Embedly/Embedly.php

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ public function apicall($version, $action, $params)
222222
}
223223

224224
$result = array();
225+
$merged_result = array();
225226

226227
if (sizeof($rejects) < sizeof($params['urls'])) {
227228
if (count($params['urls']) > 20) {
@@ -238,10 +239,34 @@ public function apicall($version, $action, $params)
238239
sprintf('Host: %s', $url_parts['hostname']),
239240
sprintf('User-Agent: %s', $this->user_agent)
240241
));
241-
$res = $this->curlExec($ch);
242+
$response_arr = $this->curlExec($ch);
243+
$http_code = $response_arr["http_code"];
244+
$res = $response_arr["response"];
242245
$result = json_decode($res) ?: array();
246+
247+
// if there's an http error code, return the error in all results
248+
if ($http_code !== 200) {
249+
// if error is returned in response use that one otherwise create new one
250+
if (count($result) > 0) {
251+
$error_obj = $result;
252+
// all results will be in rejected array
253+
$result = array();
254+
}
255+
else {
256+
$error_obj = (object)array(
257+
'error_code' => $http_code,
258+
'error_message' => sprintf('HTTP error code %s', $http_code),
259+
'type' => 'error'
260+
);
261+
}
262+
263+
// set errors in every result object
264+
foreach($params["urls"] as $i => $url) {
265+
$rejects[$i] = $error_obj;
266+
}
267+
}
243268
}
244-
$merged_result = array();
269+
245270
foreach ($result as $i => $v) {
246271
if (array_key_exists($i, $rejects)) {
247272
array_push($merged_result, array_shift($rejects));
@@ -273,7 +298,8 @@ public function services() {
273298
sprintf('Host: %s', $url['hostname']),
274299
sprintf('User-Agent: %s', $this->user_agent)
275300
));
276-
$res = $this->curlExec($ch);
301+
$response_arr = $this->curlExec($ch);
302+
$res = $response_arr["response"];
277303
$this->services = json_decode($res);
278304
}
279305
return $this->services;
@@ -322,10 +348,11 @@ protected function setCurlOptions(&$ch, $headers = array())
322348
protected function curlExec(&$ch)
323349
{
324350
$res = curl_exec($ch);
351+
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
325352
if (false === $res) {
326353
throw new \Exception(curl_error($ch), curl_errno($ch));
327354
}
328-
return $res;
355+
return array("http_code" => $http_code, "response" => $res);
329356
}
330357

331358

0 commit comments

Comments
 (0)