/** * @param $verb "GET"/"POST"/... * @param $url * @param array|null $payload * @param bool $json * @return Bf_RawAPIOutput */ private function doCurl($verb, $url, $payload, $queryParams = array()) { $curl = curl_init(); $header = array(); $payloadStr = is_null($payload) ? null : Bf_Util::associativeArrayToJsonStr($payload); $hasPayload = !is_null($payloadStr) && is_string($payloadStr); $hasQueryParams = !is_null($queryParams) && is_array($queryParams) && count($queryParams); switch ($verb) { case "POST": curl_setopt($curl, CURLOPT_POST, 1); break; case "PUT": curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); break; case "DELETE": curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); break; } if ($hasPayload) { array_push($header, "Authorization: Bearer " . $this->access_token); } else { // if we put auth in the query param: we can avoid an OPTIONS preflight if (!$hasQueryParams) { $queryParams = array(); } $queryParams['access_token'] = $this->access_token; $hasQueryParams = true; } if ($hasQueryParams) { foreach ($queryParams as $key => $value) { if (is_bool($value)) { $queryParams[$key] = $value ? 'true' : 'false'; } } $url = sprintf("%s%s%s", $url, strpos($url, '?') ? '&' : '?', http_build_query($queryParams)); } if (!is_null($this->curlProxy)) { curl_setopt($curl, CURLOPT_PROXY, $this->curlProxy); } if ($hasPayload) { // has JSON payload array_push($header, 'Content-Type: application/json; charset=UTF-8'); /* * `strlen` is fine even for UTF-8, because it counts bytes rather than characters. And bytes is indeed what curl wants. * For posterity: here are alternatives if we actually want to count characters: * mb_strlen($payloadStr, 'utf8') * mb_strlen($payloadStr) */ array_push($header, 'Content-Length: ' . strlen($payloadStr)); curl_setopt($curl, CURLOPT_POSTFIELDS, $payloadStr); } curl_setopt($curl, CURLOPT_HTTPHEADER, $header); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_ENCODING, ''); $response = curl_exec($curl); $info = curl_getinfo($curl); $error = $info === false ? curl_error($curl) : NULL; curl_close($curl); return new Bf_RawAPIOutput($info, $response, $error); }
public function getJson($jsonEncodeOptionsBitmask = 0) { if (defined('JSON_PRETTY_PRINT')) { $jsonEncodeOptionsBitmask |= JSON_PRETTY_PRINT; } return Bf_Util::associativeArrayToJsonStr($this, $jsonEncodeOptionsBitmask); }