Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add support for REST-Batch in the client library.

Remove support for JSON-RPC from the client. This leaves apiHttpRequest as the
intermediary representation of a request instead of apiServiceRequest.

Code Review: https://codereview.googleplex.com/66001/
  • Loading branch information...
commit 5f9447297bff7ce8183cc283ae8fb20b7b5d79f8 1 parent 3eafddc
chirags@google.com authored
53 examples/batch.php
View
@@ -1,11 +1,34 @@
<?php
-session_start();
+/*
+ * Copyright (c) 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
-require_once "../src/apiClient.php";
+require_once '../src/apiClient.php';
+require_once '../src/contrib/apiPlusService.php';
+session_start();
$client = new apiClient();
-$client->discover('plus');
-$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
+$client->setApplicationName("Google+ PHP Starter Application");
+$plus = new apiPlusService($client);
+
+// Visit https://code.google.com/apis/console?api=plus to generate your
+// client id, client secret, and to register your redirect uri.
+// $client->setClientId('insert_your_oauth2_client_id');
+// $client->setClientSecret('insert_your_oauth2_client_secret');
+// $client->setRedirectUri('insert_your_oauth2_redirect_uri');
+// $client->setDeveloperKey('insert_your_developer_key');
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
@@ -20,12 +43,20 @@
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
- $ret = apiBatch::execute(
- $client->plus->activities->list(array('userId' => 'me', 'collection' => 'public'), 'listActivities'),
- $client->plus->people->get(array('userId' => 'me'), 'getPerson')
- );
+}
- print "<pre>" . filter_var(print_r($ret, true), FILTER_SANITIZE_STRING) . "</pre>";
+if ($client->getAccessToken()) {
+ $client->setUseBatch(true);
+
+ $batch = new apiBatchRequest();
+ $batch->add($plus->people->get('me'), 'key1');
+ $batch->add($plus->people->get('me'), 'key2');
+ $result = $batch->execute();
+ print "<pre>" . print_r($result, true) . "</pre>";
+
+ // The access token may have been updated lazily.
+ $_SESSION['token'] = $client->getAccessToken();
} else {
- $client->authenticate();
-}
+ $authUrl = $client->createAuthUrl();
+ print "<a class='login' href='$authUrl'>Connect Me!</a>";
+}
25 src/io/apiCurlIO.php
View
@@ -39,6 +39,7 @@ class apiCurlIO implements apiIO {
CURLOPT_FAILONERROR => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HEADER => true,
+ CURLOPT_VERBOSE => false,
);
/**
@@ -129,7 +130,7 @@ public function makeRequest(apiHttpRequest $request) {
// Parse out the raw response into usable bits
list($responseHeaders, $responseBody) =
- $this->parseHttpResponseBody($respData, $respHeaderSize);
+ self::parseHttpResponse($respData, $respHeaderSize);
if ($respHttpCode == 304 && $cached) {
// If the server responded NOT_MODIFIED, return the cached request.
@@ -197,15 +198,26 @@ public function getCachedRequest(apiHttpRequest $request) {
* @param $headerSize
* @return array
*/
- public function parseHttpResponseBody($respData, $headerSize) {
+ public static function parseHttpResponse($respData, $headerSize) {
if (stripos($respData, self::CONNECTION_ESTABLISHED) !== false) {
$respData = str_ireplace(self::CONNECTION_ESTABLISHED, '', $respData);
}
- $responseBody = substr($respData, $headerSize);
- $responseHeaderLines = explode("\r\n", substr($respData, 0, $headerSize));
- $responseHeaders = array();
+ if ($headerSize) {
+ $responseBody = substr($respData, $headerSize);
+ $responseHeaders = substr($respData, 0, $headerSize);
+ } else {
+ list($responseHeaders, $responseBody) = explode("\r\n\r\n", $respData, 2);
+ }
+
+ $responseHeaders = self::parseResponseHeaders($responseHeaders);
+ return array($responseHeaders, $responseBody);
+ }
+ public static function parseResponseHeaders($rawHeaders) {
+ $responseHeaders = array();
+
+ $responseHeaderLines = explode("\r\n", $rawHeaders);
foreach ($responseHeaderLines as $headerLine) {
if ($headerLine && strpos($headerLine, ':') !== false) {
list($header, $value) = explode(': ', $headerLine, 2);
@@ -217,8 +229,7 @@ public function parseHttpResponseBody($respData, $headerSize) {
}
}
}
-
- return array($responseHeaders, $responseBody);
+ return $responseHeaders;
}
/**
45 src/io/apiHttpRequest.php
View
@@ -25,6 +25,12 @@
*/
class apiHttpRequest {
const USER_AGENT_SUFFIX = "google-api-php-client/0.5.0";
+ private $batchHeaders = array(
+ 'Content-Type' => 'application/http',
+ 'Content-Transfer-Encoding' => 'binary',
+ 'MIME-Version' => '1.0',
+ 'Content-Length' => ''
+ );
protected $url;
protected $requestMethod;
@@ -39,7 +45,7 @@ class apiHttpRequest {
public $accessKey;
public function __construct($url, $method = 'GET', $headers = array(), $postBody = null) {
- $this->url = $url;
+ $this->setUrl($url);
$this->setRequestMethod($method);
$this->setRequestHeaders($headers);
$this->setPostBody($postBody);
@@ -183,7 +189,12 @@ public function getPostBody() {
* @param string $url the url to set
*/
public function setUrl($url) {
- $this->url = $url;
+ if (substr($url, 0, 4) == 'http') {
+ $this->url = $url;
+ } else {
+ global $apiConfig;
+ $this->url = $apiConfig['basePath'] . $url;
+ }
}
/**
@@ -233,7 +244,7 @@ public function getUserAgent() {
* Returns a cache key depending on if this was an OAuth signed request
* in which case it will use the non-signed url and access key to make this
* cache key unique per authenticated user, else use the plain request url
- * @return The md5 hash of the request cache key.
+ * @return string The md5 hash of the request cache key.
*/
public function getCacheKey() {
$key = $this->getUrl();
@@ -253,10 +264,36 @@ public function getParsedCacheControl() {
$parsed = array();
$rawCacheControl = $this->getResponseHeader('cache-control');
if ($rawCacheControl) {
- $rawCacheControl = str_replace(", ", "&", $rawCacheControl);
+ $rawCacheControl = str_replace(', ', '&', $rawCacheControl);
parse_str($rawCacheControl, $parsed);
}
return $parsed;
}
+
+ /**
+ * @return string A string representation of the HTTP Request.
+ */
+ public function toBatchString($id) {
+ $str = '';
+ foreach($this->batchHeaders as $key => $val) {
+ $str .= $key . ': ' . $val . "\n";
+ }
+
+ $str .= "Content-ID: $id\n";
+ $str .= "\n";
+
+ $path = parse_url($this->getUrl(), PHP_URL_PATH);
+ $str .= $this->getRequestMethod() . ' ' . $path . " HTTP/1.1\n";
+ foreach($this->getRequestHeaders() as $key => $val) {
+ $str .= $key . ': ' . $val . "\n";
+ }
+
+ if ($this->getPostBody()) {
+ $str .= "\n";
+ $str .= $this->getPostBody();
+ }
+
+ return $str;
+ }
}
1  src/io/apiIO.php
View
@@ -18,7 +18,6 @@
require_once 'io/apiHttpRequest.php';
require_once 'io/apiCurlIO.php';
require_once 'io/apiREST.php';
-require_once 'io/apiRPC.php';
/**
* Abstract IO class
30 src/io/apiREST.php
View
@@ -15,9 +15,6 @@
* limitations under the License.
*/
-require_once "external/URITemplateParser.php";
-require_once "service/apiUtils.php";
-
/**
* This class implements the RESTful transport of apiServiceRequest()'s
*
@@ -29,30 +26,13 @@ class apiREST {
* Executes a apiServiceRequest using a RESTful call by transforming it into
* an apiHttpRequest, and executed via apiIO::authenticatedRequest().
*
- * @param apiServiceRequest $req
+ * @param apiHttpRequest $req
* @return array decoded result
- * @throws apiServiceException on server side error (ie: not authenticated, invalid or
- * malformed post body, invalid url)
+ * @throws apiServiceException on server side error (ie: not authenticated,
+ * invalid or malformed post body, invalid url)
*/
- static public function execute(apiServiceRequest $req) {
- $result = null;
- $postBody = $req->getPostBody();
- $url = self::createRequestUri(
- $req->getRestBasePath(), $req->getRestPath(), $req->getParameters());
-
- $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody);
- if ($postBody) {
- $contentTypeHeader = array();
- if (isset($req->contentType) && $req->contentType) {
- $contentTypeHeader['content-type'] = $req->contentType;
- } else {
- $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
- $contentTypeHeader['content-length'] = apiUtils::getStrLen($postBody);
- }
- $httpRequest->setRequestHeaders($contentTypeHeader);
- }
-
- $httpRequest = apiClient::$io->authenticatedRequest($httpRequest);
+ static public function execute(apiHttpRequest $req) {
+ $httpRequest = apiClient::$io->makeRequest($req);
$decodedResponse = self::decodeHttpResponse($httpRequest);
//FIXME currently everything is wrapped in a data envelope, but hopefully this might change some day
63 src/io/apiRPC.php
View
@@ -1,63 +0,0 @@
-<?php
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * This class implements the experimental JSON-RPC transport for executing apiServiceRequest'
- *
- * @author Chris Chabot <chabotc@google.com>
- */
-class apiRPC {
- static public function execute($requests) {
- $jsonRpcRequest = array();
- foreach ($requests as $request) {
- $parameters = array();
- foreach ($request->getParameters() as $parameterName => $parameterVal) {
- $parameters[$parameterName] = $parameterVal['value'];
- }
- $jsonRpcRequest[] = array(
- 'id' => $request->getBatchKey(),
- 'method' => $request->getRpcName(),
- 'params' => $parameters,
- 'apiVersion' => 'v1'
- );
- }
- $httpRequest = new apiHttpRequest($request->getRpcPath());
- $httpRequest->setRequestHeaders(array('Content-Type' => 'application/json'));
- $httpRequest->setRequestMethod('POST');
- $httpRequest->setPostBody(json_encode($jsonRpcRequest));
- $httpRequest = apiClient::$io->authenticatedRequest($httpRequest);
- if (($decodedResponse = json_decode($httpRequest->getResponseBody(), true)) != false) {
- $ret = array();
- foreach ($decodedResponse as $response) {
- $ret[$response['id']] = self::checkNextLink($response['result']);
- }
- return $ret;
- } else {
- throw new apiServiceException("Invalid json returned by the json-rpc end-point");
- }
- }
-
- static private function checkNextLink($response) {
- if (isset($response['links']) && isset($response['links']['next'][0]['href'])) {
- parse_str($response['links']['next'][0]['href'], $params);
- if (isset($params['c'])) {
- $response['continuationToken'] = $params['c'];
- }
- }
- return $response;
- }
-}
39 src/service/apiBatch.php
View
@@ -1,39 +0,0 @@
-<?php
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * Wrapper for the (experimental!) JSON-RPC protocol, for production use regular REST calls instead
- *
- * @author Chris Chabot <chabotc@google.com>
- */
-class apiBatch {
-
- /**
- * Execute one or multiple Google API requests, takes one or multiple requests as param
- * Example usage:
- * $ret = apiBatch::execute(
- * $apiClient->activities->list(array('@public', '@me'), 'listActivitiesKey'),
- * $apiClient->people->get(array('userId' => '@me'), 'getPeopleKey')
- * );
- * print_r($ret['getPeopleKey']);
- */
- static public function execute( /* polymorphic */) {
- $requests = func_get_args();
- return apiRPC::execute($requests);
- }
-
-}
110 src/service/apiBatchRequest.php
View
@@ -0,0 +1,110 @@
+<?php
+/*
+ * Copyright 2012 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Chirag Shah <chirags@google.com>
+ */
+class apiBatchRequest {
+ /** @var string Multipart Boundary. */
+ private $boundary;
+
+ /** @var array service requests to be executed. */
+ private $requests = array();
+
+ public function __construct($boundary = false) {
+ $boundary = (false == $boundary) ? mt_rand() : $boundary;
+ $this->boundary = str_replace('"', '', $boundary);
+ }
+
+ public function add(apiHttpRequest $request, $key = false) {
+ if (false == $key) {
+ $key = mt_rand();
+ }
+
+ $this->requests[$key] = $request;
+ }
+
+ public function execute() {
+ $body = '';
+
+ /** @var apiHttpRequest $req */
+ foreach($this->requests as $key => $req) {
+ $body .= "--{$this->boundary}\n";
+ $body .= $req->toBatchString($key) . "\n";
+ }
+
+ $body = rtrim($body);
+ $body .= "\n--{$this->boundary}--";
+
+ global $apiConfig;
+ $url = $apiConfig['basePath'] . '/batch';
+ $httpRequest = new apiHttpRequest($url, 'POST');
+ $httpRequest->setRequestHeaders(array(
+ 'Content-Type' => 'multipart/mixed; boundary=' . $this->boundary));
+
+ $httpRequest->setPostBody($body);
+ $response = apiClient::$io->makeRequest($httpRequest);
+
+ $response = $this->parseResponse($response);
+ return $response;
+ }
+
+ public function parseResponse(apiHttpRequest $response) {
+ $contentType = $response->getResponseHeader('content-type');
+ $contentType = explode(';', $contentType);
+ $boundary = false;
+ foreach($contentType as $part) {
+ $part = (explode('=', $part, 2));
+ if (isset($part[0]) && 'boundary' == trim($part[0])) {
+ $boundary = $part[1];
+ }
+ }
+
+ $body = $response->getResponseBody();
+ if ($body) {
+ $body = str_replace("--$boundary--", "--$boundary", $body);
+ $parts = explode("--$boundary", $body);
+ $responses = array();
+
+ foreach($parts as $part) {
+ $part = trim($part);
+ if (!empty($part)) {
+ list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
+ $metaHeaders = apiCurlIO::parseResponseHeaders($metaHeaders);
+
+ $status = substr($part, 0, strpos($part, "\n"));
+ $status = explode(" ", $status);
+ $status = $status[1];
+
+ list($partHeaders, $partBody) = apiCurlIO::parseHttpResponse($part, false);
+ $response = new apiHttpRequest("");
+ $response->setResponseHttpCode($status);
+ $response->setResponseHeaders($partHeaders);
+ $response->setResponseBody($partBody);
+ $response = apiREST::decodeHttpResponse($response);
+
+ // Need content id.
+ $responses[$metaHeaders['content-id']] = $response;
+ }
+ }
+
+ return $responses;
+ }
+
+ return null;
+ }
+}
23 src/service/apiMediaFileUpload.php
View
@@ -195,7 +195,7 @@ public static function getUploadType($meta, &$payload, &$params) {
}
- public function nextChunk(apiServiceRequest $req) {
+ public function nextChunk(apiHttpRequest $req) {
if (false == $this->resumeUri) {
$this->resumeUri = $this->getResumeUri($req);
}
@@ -204,7 +204,7 @@ public function nextChunk(apiServiceRequest $req) {
$lastBytePos = $this->progress + strlen($data) - 1;
$headers = array(
'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
- 'content-type' => $req->contentType,
+ 'content-type' => $req->getRequestHeader('content-type'),
'content-length' => $this->chunkSize,
'expect' => '',
);
@@ -221,28 +221,19 @@ public function nextChunk(apiServiceRequest $req) {
}
}
- private function getResumeUri(apiServiceRequest $req) {
+ private function getResumeUri(apiHttpRequest $httpRequest) {
$result = null;
- $postBody = $req->getPostBody();
- $url = apiREST::createRequestUri(
- $req->getRestBasePath(),
- $req->getRestPath(),
- $req->getParameters()
- );
-
- $httpRequest = new apiHttpRequest(
- $url, $req->getHttpMethod(), null, $postBody);
-
- if ($postBody) {
+ $body = $httpRequest->getPostBody();
+ if ($body) {
$httpRequest->setRequestHeaders(array(
'content-type' => 'application/json; charset=UTF-8',
- 'content-length' => apiUtils::getStrLen($postBody),
+ 'content-length' => apiUtils::getStrLen($body),
'x-upload-content-type' => $this->mimeType,
'expect' => '',
));
}
- $response = apiClient::$io->authenticatedRequest($httpRequest);
+ $response = apiClient::$io->makeRequest($httpRequest);
$location = $response->getResponseHeader('location');
$code = $response->getResponseHttpCode();
if (200 == $code && true == $location) {
46 src/service/apiService.php
View
@@ -15,50 +15,8 @@
* limitations under the License.
*/
-require_once 'service/apiServiceResource.php';
-require_once 'service/apiServiceRequest.php';
-require_once 'service/apiBatch.php';
-
-/**
- * This class parses the service end points of the api discovery document and constructs
- * serviceResource variables for all of them.
- *
- * For instance when calling with the service document for Plus, it will create apiServiceResource's
- * for $this->activities, $this->comments, $this->people, etc.
- *
- * @author Chris Chabot <chabotc@google.com>
- *
- */
class apiService {
- public $version = null;
+ public $version;
public $restBasePath;
- public $rpcPath;
- public $resource = null;
-
- public function __construct($serviceName, $discoveryDocument) {
- global $apiConfig;
- if (!isset($discoveryDocument['version']) || !isset($discoveryDocument['restBasePath']) || !isset($discoveryDocument['rpcPath'])) {
- throw new apiServiceException("Invalid discovery document");
- }
- $this->version = $discoveryDocument['version'];
- $this->restBasePath = $apiConfig['basePath'] . $discoveryDocument['restBasePath'];
- $this->rpcPath = $apiConfig['basePath'] . $discoveryDocument['rpcPath'];
- foreach ($discoveryDocument['resources'] as $resourceName => $resourceTypes) {
- $this->$resourceName = new apiServiceResource($this, $serviceName, $resourceName, $resourceTypes);
- }
- }
-
- /**
- * @return string $restBasePath
- */
- public function getRestBasePath() {
- return $this->restBasePath;
- }
-
- /**
- * @return string $rpcPath
- */
- public function getRpcPath() {
- return $this->rpcPath;
- }
+ public $resource;
}
135 src/service/apiServiceRequest.php
View
@@ -1,135 +0,0 @@
-<?php
-
-/*
- * Copyright 2010 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * Internal representation of a Google API request, used by the apiServiceResource class to
- * construct API function calls and passing them to the IO layer who knows how to execute
- * the request
- *
- * @author Chris Chabot <chabotc@google.com>
- * @author Chirag Shah <chirags@google.com>
- *
- */
-class apiServiceRequest {
- public $restBasePath;
- public $restPath;
- public $rpcPath;
- public $rpcName;
- public $httpMethod;
- public $parameters;
- public $postBody;
- public $batchKey;
- public $contentType;
-
- /**
- * @param string $restBasePath
- * @param string $rpcPath
- * @param string $restPath
- * @param string $rpcName
- * @param string $httpMethod
- * @param array $parameters
- * @param string $postBody
- */
- public function __construct($restBasePath, $rpcPath, $restPath, $rpcName, $httpMethod, $parameters, $postBody = null) {
- if (substr($restBasePath, 0, 4) == 'http') {
- $this->restBasePath = $restBasePath;
- } else {
- global $apiConfig;
- $this->restBasePath = $apiConfig['basePath'] . $restBasePath;
- }
-
- $this->restPath = $restPath;
- $this->rpcPath = $rpcPath;
- $this->rpcName = $rpcName;
- $this->httpMethod = $httpMethod;
- $this->parameters = $parameters;
- $this->postBody = $postBody;
- }
-
- /**
- * @return string $postBody
- */
- public function getPostBody() {
- return $this->postBody;
- }
-
- /**
- * @param string $postBody The post body.
- */
- public function setPostBody($postBody) {
- $this->postBody = $postBody;
- }
- /**
- * @return string restBasePath
- */
- public function getRestBasePath() {
- return $this->restBasePath;
- }
- /**
- * @return string restPath
- */
- public function getRestPath() {
- return $this->restPath;
- }
-
- /**
- * @return string $rpcPath
- */
- public function getRpcPath() {
- return $this->rpcPath;
- }
-
- /**
- * @return string $rpcName
- */
- public function getRpcName() {
- return $this->rpcName;
- }
-
- /**
- * @return string $httpMethod
- */
- public function getHttpMethod() {
- return $this->httpMethod;
- }
-
- /**
- * @return array $parameters
- */
- public function getParameters() {
- return $this->parameters;
- }
-
- /**
- * @return string $batchKey
- */
- public function getBatchKey() {
- return $this->batchKey;
- }
-
- /**
- * @param $batchKey the $batchKey to set
- */
- public function setBatchKey($batchKey) {
- $this->batchKey = $batchKey;
- }
-
- public function setContentType($type) {
- $this->contentType = $type;
- }
-}
53 src/service/apiServiceResource.php
View
@@ -18,7 +18,7 @@
/**
* Implements the actual methods/resources of the discovered Google API using magic function
* calling overloading (__call()), which on call will see if the method name (plus.activities.list)
- * is available in this service, and if so construct an apiServiceRequest representing it.
+ * is available in this service, and if so construct an apiHttpRequest representing it.
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
@@ -62,28 +62,16 @@ public function __construct($service, $serviceName, $resourceName, $resource) {
/**
* @param $name
* @param $arguments
- * @return apiServiceRequest|array
+ * @return apiHttpRequest|array
* @throws apiException
*/
public function __call($name, $arguments) {
- if (count($arguments) != 1 && count($arguments) != 2) {
- throw new apiException("client method calls expect 1 or 2 parameter (\$client->plus->activities->list(array('userId' => 'me'))");
- }
- if (! is_array($arguments[0])) {
- throw new apiException("client method parameter should be an array (\$client->plus->activities->list(array('userId' => 'me'))");
- }
- $batchKey = false;
- if (isset($arguments[1])) {
- if (! is_string($arguments[1])) {
- throw new apiException("The batch key parameter should be a string (\$client->plus->activities->list( array('userId' => 'me'), 'batchKey'))");
- }
- $batchKey = $arguments[1];
- }
if (! isset($this->methods[$name])) {
throw new apiException("Unknown function: {$this->serviceName}->{$this->resourceName}->{$name}()");
}
$method = $this->methods[$name];
$parameters = $arguments[0];
+
// postBody is a special case since it's not defined in the discovery document as parameter, but we abuse the param entry for storing it
$postBody = null;
if (isset($parameters['postBody'])) {
@@ -162,29 +150,32 @@ public function __call($name, $arguments) {
}
}
- $request = new apiServiceRequest(
- $restBasePath,
- $this->service->rpcPath,
- $method['path'],
- $method['id'],
- $method['httpMethod'],
- $parameters, $postBody
- );
+ $url = apiREST::createRequestUri($restBasePath, $method['path'], $parameters);
- $request->setContentType($contentType);
+ $httpRequest = new apiHttpRequest($url, $method['httpMethod'], null, $postBody);
+ if ($postBody) {
+ $contentTypeHeader = array();
+ if (isset($contentType) && $contentType) {
+ $contentTypeHeader['content-type'] = $contentType;
+ } else {
+ $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
+ $contentTypeHeader['content-length'] = apiUtils::getStrLen($postBody);
+ }
+ $httpRequest->setRequestHeaders($contentTypeHeader);
+ }
+
+ $httpRequest = apiClient::$auth->sign($httpRequest);
+ if (apiClient::$useBatch) {
+ return $httpRequest;
+ }
// Terminate immediatly if this is a resumable request.
if (isset($parameters['uploadType']['value'])
&& 'resumable' == $parameters['uploadType']['value']) {
- return $request;
+ return $httpRequest;
}
- if ($batchKey) {
- $request->setBatchKey($batchKey);
- return $request;
- } else {
- return apiREST::execute($request);
- }
+ return apiREST::execute($httpRequest);
}
protected function useObjects() {
4 test/AllTests.php
View
@@ -23,6 +23,7 @@
*/
require_once 'BaseTest.php';
+require_once 'adsense/AdsenseTest.php';
require_once 'general/GeneralTests.php';
require_once 'tasks/AllTasksTests.php';
require_once 'pagespeed/AllPageSpeedTests.php';
@@ -37,8 +38,9 @@ public static function suite() {
$suite->addTestSuite(AllPageSpeedTests::suite());
$suite->addTestSuite(AllUrlShortenerTests::suite());
$suite->addTestSuite(AllPlusTests::suite());
- $suite->addTestSuite(GeneralTests::suite());
$suite->addTestSuite(AdsenseTests::suite());
+
+ $suite->addTestSuite(GeneralTests::suite());
return $suite;
}
}
45 test/general/ApiBatchRequestTest.php
View
@@ -0,0 +1,45 @@
+<?php
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+require_once 'BaseTest.php';
+require_once '../src/contrib/apiPlusService.php';
+require_once '../src/service/apiBatchRequest.php';
+
+class ApiBatchRequestTest extends BaseTest {
+ public $plus;
+ public function __construct() {
+ parent::__construct();
+ $this->plus = new apiPlusService(BaseTest::$client);
+ }
+
+ public function testBatchRequest() {
+ $batch = new apiBatchRequest();
+
+ BaseTest::$client->setUseBatch(true);
+ $batch->add($this->plus->people->get('me'), 'key1');
+ $batch->add($this->plus->people->get('me'), 'key2');
+ $batch->add($this->plus->people->get('me'), 'key3');
+
+ $result = $batch->execute();
+ $this->assertTrue(isset($result['key1']));
+ $this->assertTrue(isset($result['key2']));
+ $this->assertTrue(isset($result['key3']));
+ }
+}
13 test/general/ApiClientTest.php
View
@@ -19,9 +19,16 @@
*/
class ApiClientTest extends BaseTest {
- public function testDummy() {
+ public function testClient() {
// temp place holder as tests are being filled in
- $this->assertTrue(true);
- }
+ $client = new apiClient();
+ $client->setAccessType('foo');
+ $this->assertEquals('foo', $client->getAuth()->accessType);
+
+ $client->setDeveloperKey('foo');
+ $this->assertEquals('foo', $client->getAuth()->developerKey);
+ $client->setAccessToken(json_encode(array('access_token' => '1')));
+ $this->assertEquals("{\"access_token\":\"1\"}", $client->getAccessToken());
+ }
}
38 test/general/ApiOAuth2Test.php
View
@@ -23,40 +23,44 @@
require_once "io/apiREST.php";
class ApiOAuth2Test extends BaseTest {
- /** @var apiOAuth2 $auth */
- private $auth;
-
- public function setUp() {
- $this->auth = new apiOAuth2();
- $this->auth->developerKey = "devKey";
- $this->auth->clientId = "clientId1";
- $this->auth->clientSecret = "clientSecret1";
- $this->auth->redirectUri = "http://localhost";
+ public function testSign() {
+ $oauth = new apiOAuth2();
- $this->auth->approvalPrompt = 'force';
- $this->auth->accessType = "offline";
- }
+ $oauth->developerKey = "devKey";
+ $oauth->clientId = "clientId1";
+ $oauth->clientSecret = "clientSecret1";
+ $oauth->redirectUri = "http://localhost";
+ $oauth->approvalPrompt = 'force';
+ $oauth->accessType = "offline";
- public function testSign() {
$req = new apiHttpRequest('http://localhost');
- $req = $this->auth->sign($req);
+ $req = $oauth->sign($req);
$this->assertEquals('http://localhost?key=devKey', $req->getUrl());
// test accessToken
- $this->auth->accessToken = array(
+ $oauth->accessToken = array(
'access_token' => 'ACCESS_TOKEN',
'created' => time(),
'expires_in' => '3600'
);
- $req = $this->auth->sign($req);
+ $req = $oauth->sign($req);
$auth = $req->getRequestHeader('authorization');
$this->assertEquals('Bearer ACCESS_TOKEN', $auth);
}
public function testCreateAuthUrl() {
- $authUrl = $this->auth->createAuthUrl("http://googleapis.com/scope/foo");
+ $oauth = new apiOAuth2();
+
+ $oauth->developerKey = "devKey";
+ $oauth->clientId = "clientId1";
+ $oauth->clientSecret = "clientSecret1";
+ $oauth->redirectUri = "http://localhost";
+ $oauth->approvalPrompt = 'force';
+ $oauth->accessType = "offline";
+
+ $authUrl = $oauth->createAuthUrl("http://googleapis.com/scope/foo");
$expected = "https://accounts.google.com/o/oauth2/auth"
. "?response_type=code"
. "&redirect_uri=http%3A%2F%2Flocalhost"
6 test/general/IoTest.php
View
@@ -30,14 +30,14 @@ public function testParseHttpResponseBody() {
$rawBody = "{}";
$rawResponse = "$rawHeaders\r\n$rawBody";
- list($headers, $body) = $io->parseHttpResponseBody($rawResponse, $size);
+ list($headers, $body) = $io->parseHttpResponse($rawResponse, $size);
$this->assertEquals(3, sizeof($headers));
$this->assertEquals(array(), json_decode($body, true));
// Test empty bodies.
$rawResponse = $rawHeaders . "\r\n";
- list($headers, $body) = $io->parseHttpResponseBody($rawResponse, $size);
+ list($headers, $body) = $io->parseHttpResponse($rawResponse, $size);
$this->assertEquals(3, sizeof($headers));
$this->assertEquals(null, json_decode($body, true));
@@ -48,7 +48,7 @@ public function testParseHttpResponseBody() {
$rawResponse = apiCurlIO::CONNECTION_ESTABLISHED
. "$rawHeaders\r\n$rawBody";
- list($headers, $body) = $io->parseHttpResponseBody($rawResponse, $size);
+ list($headers, $body) = $io->parseHttpResponse($rawResponse, $size);
$this->assertEquals(1, sizeof($headers));
$this->assertEquals(array(), json_decode($body, true));
}
22 test/urlshortener/UrlShortenerTests.php
View
@@ -24,8 +24,6 @@ class UrlShortenerTests extends BaseTest {
public function __construct() {
parent::__construct();
$this->service = new apiUrlshortenerService(BaseTest::$client);
-
- BaseTest::$client->discover('urlshortener');
}
public function testUrlShort() {
@@ -36,24 +34,4 @@ public function testUrlShort() {
$this->assertEquals('urlshortener#url', $shortUrl['kind']);
$this->assertEquals('http://google.com/', $shortUrl['longUrl']);
}
-
- public function testRpcBatch() {
- $url = new Url();
- $url->longUrl = "http://google.com";
- $short0 = $this->service->url->insert($url);
-
- $url = new Url();
- $url->longUrl = "http://www.google.com";
- $short1 = $this->service->url->insert($url);
-
- $ret = apiBatch::execute(
- BaseTest::$client->urlshortener->url->get(array('shortUrl' => $short0['id']), 'url0'),
- BaseTest::$client->urlshortener->url->get(array('shortUrl' => $short1['id']), 'url1')
- );
-
- $this->assertArrayHasKey('url0', $ret);
- $this->assertArrayHasKey('url1', $ret);
- $this->assertArrayHasKey('id', $ret['url0']);
- $this->assertArrayHasKey('longUrl', $ret['url0']);
- }
}
Please sign in to comment.
Something went wrong with that request. Please try again.