PageRenderTime 41ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/google/src/Google/Http/REST.php

https://gitlab.com/unofficial-mirrors/moodle
PHP | 178 lines | 104 code | 16 blank | 58 comment | 26 complexity | f7a9168f3e285cd4617322bdc844df4a MD5 | raw file
  1. <?php
  2. /*
  3. * Copyright 2010 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. if (!class_exists('Google_Client')) {
  18. require_once dirname(__FILE__) . '/../autoload.php';
  19. }
  20. /**
  21. * This class implements the RESTful transport of apiServiceRequest()'s
  22. */
  23. class Google_Http_REST
  24. {
  25. /**
  26. * Executes a Google_Http_Request and (if applicable) automatically retries
  27. * when errors occur.
  28. *
  29. * @param Google_Client $client
  30. * @param Google_Http_Request $req
  31. * @return array decoded result
  32. * @throws Google_Service_Exception on server side error (ie: not authenticated,
  33. * invalid or malformed post body, invalid url)
  34. */
  35. public static function execute(Google_Client $client, Google_Http_Request $req)
  36. {
  37. $runner = new Google_Task_Runner(
  38. $client,
  39. sprintf('%s %s', $req->getRequestMethod(), $req->getUrl()),
  40. array(get_class(), 'doExecute'),
  41. array($client, $req)
  42. );
  43. return $runner->run();
  44. }
  45. /**
  46. * Executes a Google_Http_Request
  47. *
  48. * @param Google_Client $client
  49. * @param Google_Http_Request $req
  50. * @return array decoded result
  51. * @throws Google_Service_Exception on server side error (ie: not authenticated,
  52. * invalid or malformed post body, invalid url)
  53. */
  54. public static function doExecute(Google_Client $client, Google_Http_Request $req)
  55. {
  56. $httpRequest = $client->getIo()->makeRequest($req);
  57. $httpRequest->setExpectedClass($req->getExpectedClass());
  58. return self::decodeHttpResponse($httpRequest, $client);
  59. }
  60. /**
  61. * Decode an HTTP Response.
  62. * @static
  63. * @throws Google_Service_Exception
  64. * @param Google_Http_Request $response The http response to be decoded.
  65. * @param Google_Client $client
  66. * @return mixed|null
  67. */
  68. public static function decodeHttpResponse($response, Google_Client $client = null)
  69. {
  70. $code = $response->getResponseHttpCode();
  71. $body = $response->getResponseBody();
  72. $decoded = null;
  73. if ((intVal($code)) >= 300) {
  74. $decoded = json_decode($body, true);
  75. $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
  76. if (isset($decoded['error']) &&
  77. isset($decoded['error']['message']) &&
  78. isset($decoded['error']['code'])) {
  79. // if we're getting a json encoded error definition, use that instead of the raw response
  80. // body for improved readability
  81. $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
  82. } else {
  83. $err .= ": ($code) $body";
  84. }
  85. $errors = null;
  86. // Specific check for APIs which don't return error details, such as Blogger.
  87. if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
  88. $errors = $decoded['error']['errors'];
  89. }
  90. $map = null;
  91. if ($client) {
  92. $client->getLogger()->error(
  93. $err,
  94. array('code' => $code, 'errors' => $errors)
  95. );
  96. $map = $client->getClassConfig(
  97. 'Google_Service_Exception',
  98. 'retry_map'
  99. );
  100. }
  101. throw new Google_Service_Exception($err, $code, null, $errors, $map);
  102. }
  103. // Only attempt to decode the response, if the response code wasn't (204) 'no content'
  104. if ($code != '204') {
  105. if ($response->getExpectedRaw()) {
  106. return $body;
  107. }
  108. $decoded = json_decode($body, true);
  109. if ($decoded === null || $decoded === "") {
  110. $error = "Invalid json in service response: $body";
  111. if ($client) {
  112. $client->getLogger()->error($error);
  113. }
  114. throw new Google_Service_Exception($error);
  115. }
  116. if ($response->getExpectedClass()) {
  117. $class = $response->getExpectedClass();
  118. $decoded = new $class($decoded);
  119. }
  120. }
  121. return $decoded;
  122. }
  123. /**
  124. * Parse/expand request parameters and create a fully qualified
  125. * request uri.
  126. * @static
  127. * @param string $servicePath
  128. * @param string $restPath
  129. * @param array $params
  130. * @return string $requestUrl
  131. */
  132. public static function createRequestUri($servicePath, $restPath, $params)
  133. {
  134. $requestUrl = $servicePath . $restPath;
  135. $uriTemplateVars = array();
  136. $queryVars = array();
  137. foreach ($params as $paramName => $paramSpec) {
  138. if ($paramSpec['type'] == 'boolean') {
  139. $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
  140. }
  141. if ($paramSpec['location'] == 'path') {
  142. $uriTemplateVars[$paramName] = $paramSpec['value'];
  143. } else if ($paramSpec['location'] == 'query') {
  144. if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
  145. foreach ($paramSpec['value'] as $value) {
  146. $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
  147. }
  148. } else {
  149. $queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
  150. }
  151. }
  152. }
  153. if (count($uriTemplateVars)) {
  154. $uriTemplateParser = new Google_Utils_URITemplate();
  155. $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
  156. }
  157. if (count($queryVars)) {
  158. $requestUrl .= '?' . implode($queryVars, '&');
  159. }
  160. return $requestUrl;
  161. }
  162. }