Skip to content

Instantly share code, notes, and snippets.

@navarr
Created May 11, 2014 01:18
Show Gist options
  • Save navarr/a4598bc709d9e2fa5855 to your computer and use it in GitHub Desktop.
Save navarr/a4598bc709d9e2fa5855 to your computer and use it in GitHub Desktop.
Did I program this? Because I am *not* proud of it
<?php
class Rest
{
public $host = null;
public $verb = null;
public $path = null;
public $scheme = 'http';
public $params = array();
public $post = array();
public static function init() { return new Rest(); }
function __construct($copyFrom = null)
{
if($copyFrom === null) return;
$this->host = $copyFrom->host;
$this->verb = $copyFrom->verb;
$this->path = $copyFrom->path;
$this->scheme = $copyFrom->scheme;
$this->params = $copyFrom->params;
$this->post = $copyFrom->post;
}
function __get($var)
{
if($this->verb === null)
{
$rest = new Rest($this);
if($rest->host === null) $rest->host = $var;
else $rest->host = $var . '.' . $rest->host;
}
else
{
$rest = new Rest($this);
$rest->path = $this->path . '/' . $var;
}
return $rest;
}
function __call($name,$arguments = null)
{
if($this->verb === null)
{
$rest = new Rest($this);
$rest->verb = $name;
if(isset($arguments[0])) $rest->post = $arguments[0];
return $rest;
}
else
{
// Okay, we've called a page. Now we do the magic.
$rest = new Rest($this);
$rest->path = $this->path . '/' . $name;
if(isset($arguments[0])) $rest->params = $arguments[0];
return $rest->_getContents();
}
}
public function _getContents()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_buildUrl());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($this->verb));
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->post);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public function _buildUrl()
{
$url = $this->scheme . '://' . $this->host . $this->path . '?' . http_build_query($this->params);
return $url;
}
}
class SecureRest extends Rest
{
public $scheme = 'https';
public static function init() { return new SecureRest(); }
}
<?php
require_once("REST.php");
//$rest = Rest::init()->com->google->www->get()->imghp(array("tab" => "wi"));
//$rest = Rest::init()->com->google->www->get()->search(array("q" => "meow"));
//var_dump($rest->_buildUrl());
//$rest = $rest->com->google->get();
//$rest->search(array("q" => "moo?"));
Rest::init()->com->twitter->api->post(array("status" => "Some status"))->{'1'}->statuses->{'update.json'}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment