url . ']'; } public function __construct ($apiPath, $action, $method='GET') { if (!is_string($action)) { throw new InvalidArgumentException('$action must be a string'); } $this->apiPath = $apiPath; $this->action = $action; $this->url = Static::$baseURL.'/'.$apiPath.'/'.$action; if (preg_match('~//.*//~',$this->url) === 1) { throw new InvalidArgumentException('Resulting URL ('.$this->url.') contains a double slash'); } if (!is_string($method)) { throw new InvalidArgumentException('$method must be a string'); } switch ($method) { case 'GET': case 'POST': case 'PUT': case 'DELETE': break; throw new InvalidArgumentException('$method must be one of the following: "GET", "POST", "PUT", "DELETE"'); } $this->method = $method; } public function exec ($dataToSend=null) { $opts = array('http' => array( 'method' => $this->method ) ); if (!is_null($dataToSend)) { if (is_array($dataToSend)) { $opts['http']['content'] = http_build_query($dataToSend); } else { throw new InvalidArgumentException('$dataToSend must be either NULL or an array'); } } $context = stream_context_create($opts); $json = @file_get_contents( $this->url, false, $context ); // Make the HTTP response header available if they want to get it // If there is no network connection, $http_response_header may be undefined if (isset($http_response_header)) { $this->http_response_header = $http_response_header; } else { $this->http_response_header = null; } $result = json_decode($json, true); switch (json_last_error()) { case JSON_ERROR_NONE: return $result; break; case JSON_ERROR_SYNTAX: throw new Exception('Result was not valid JSON: ' . json_last_error_msg()); break; default: throw new Exception('Result could not be parsed as JSON: ' . json_last_error_msg()); break; } return null; } public function getHttpResponseHeader () { return $this->http_response_header; } } ?>