Skip to content

Instantly share code, notes, and snippets.

@collegeman
Last active November 22, 2017 14:54
Show Gist options
  • Save collegeman/41b6b9c63f921776a5cfbf030409bcdd to your computer and use it in GitHub Desktop.
Save collegeman/41b6b9c63f921776a5cfbf030409bcdd to your computer and use it in GitHub Desktop.
Super basic magic method for creating REST API clients in PHP
<?php
use Requests;
/**
* Instances of this class can be invoked with any of the HTTP request
* method names (get, post, put, delete, head, etc.), and doing so builds
* and invokes a request using the Requests library.
* @see https://github.com/rmccue/Requests
*/
abstract RestClient {
protected $apiKey;
protected $baseUrl;
function __call($name, $args)
{
$method = strtolower($name);
$headers = [];
$data = null;
$path = '';
$options = [ 'auth' => [ $this->apiKey, '' ] ];
$url = $this->baseUrl;
if (!empty($args[0])) {
$url .= '/' . ltrim($args[0], '/');
}
if (!empty($args[2])) {
$headers = $args[2];
}
if (!empty($args[1])) {
$data = $args[1];
}
if (!empty($args[3])) {
$options = array_merge($options, $args[3]);
}
$args = [ $url, $headers ];
if ($method === 'post' || $method === 'put') {
$args[] = $data;
} else if (!empty($data)) {
$url .= '?' . http_build_query($data);
}
$args[] = $options;
$response = call_user_func_array("Requests::{$method}", $args);
if ($response->status_code >= 300) {
if ($errorData = json_decode($response->body)) {
$error = $errorData->error;
if (is_array($error)) {
$error = $error[0];
}
throw new \Exception($error, $response->status_code);
} else {
throw new \Exception($response->body, $response->status_code);
}
}
return json_decode($response->body);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment