Skip to content

Instantly share code, notes, and snippets.

@lfbittencourt
Last active December 4, 2017 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lfbittencourt/aed1f716b128009fdb04a13939a24333 to your computer and use it in GitHub Desktop.
Save lfbittencourt/aed1f716b128009fdb04a13939a24333 to your computer and use it in GitHub Desktop.
Simple REST API abstraction
<?php
class SimpleApi
{
private $baseUrl;
public function __construct($baseUrl)
{
$this->baseUrl = $baseUrl;
}
public function call($method, $path, array $params = [])
{
$handler = curl_init();
$url = $this->baseUrl . $path;
$headers = [
'Content-Type: application/json',
];
if ($method === 'GET' && count($params) > 0) {
$query = http_build_query($params);
if (strpos($url, '?') === false) {
$url .= '?' . $query;
} else {
$url .= '&' . $query;
}
}
curl_setopt($handler, CURLOPT_URL, $url);
curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handler, CURLOPT_FOLLOWLOCATION, true);
if (in_array($method, ['POST', 'PUT', 'DELETE'])) {
$requestBody = json_encode($params);
if ($method === 'POST') {
curl_setopt($handler, CURLOPT_POST, true);
} else {
curl_setopt($handler, CURLOPT_CUSTOMREQUEST, $method);
}
curl_setopt($handler, CURLOPT_POSTFIELDS, $requestBody);
$headers[] = 'Content-Length: ' . strlen($requestBody);
}
curl_setopt($handler, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($handler);
curl_close($handler);
$json = json_decode($response);
if (is_object($json) || is_array($json)) {
return $json;
}
error_log($response);
return null;
}
public function delete($path, array $params = [])
{
return $this->call('DELETE', $path, $params);
}
public function get($path, array $params = [])
{
return $this->call('GET', $path, $params);
}
public function post($path, array $params = [])
{
return $this->call('POST', $path, $params);
}
public function put($path, array $params = [])
{
return $this->call('PUT', $path, $params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment