GetResponseTrait.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <?php
  2. /**
  3. * Copyright 2019 Huawei Technologies Co.,Ltd.
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  5. * this file except in compliance with the License. You may obtain a copy of the
  6. * License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed
  11. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. * specific language governing permissions and limitations under the License.
  14. *
  15. */
  16. namespace Obs\Internal;
  17. use GuzzleHttp\Exception\RequestException;
  18. use GuzzleHttp\Psr7\Request;
  19. use GuzzleHttp\Psr7\Response;
  20. use Obs\Internal\Common\CheckoutStream;
  21. use Obs\Internal\Common\Model;
  22. use Obs\Internal\Resource\Constants;
  23. use Obs\Log\ObsLog;
  24. use Obs\ObsException;
  25. use Psr\Http\Message\StreamInterface;
  26. trait GetResponseTrait
  27. {
  28. protected $exceptionResponseMode = true;
  29. protected $chunkSize = 65536;
  30. protected function isClientError(Response $response)
  31. {
  32. return $response->getStatusCode() >= 400 && $response->getStatusCode() < 500;
  33. }
  34. protected function parseXmlByType($searchPath, $key, &$value, $xml, $prefix)
  35. {
  36. $type = 'string';
  37. if (isset($value['sentAs'])) {
  38. $key = $value['sentAs'];
  39. }
  40. if ($searchPath === null) {
  41. $searchPath = '//' . $prefix . $key;
  42. }
  43. if (isset($value['type'])) {
  44. $type = $value['type'];
  45. if ($type === 'array') {
  46. $items = $value['items'];
  47. if (isset($value['wrapper'])) {
  48. $paths = explode('/', $searchPath);
  49. $size = count($paths);
  50. if ($size > 1) {
  51. $end = $paths[$size - 1];
  52. $paths[$size - 1] = $value['wrapper'];
  53. $paths[] = $end;
  54. $searchPath = implode('/', $paths) . '/' . $prefix;
  55. }
  56. }
  57. $array = [];
  58. if (!isset($value['data']['xmlFlattened'])) {
  59. $pkey = isset($items['sentAs']) ? $items['sentAs'] : $items['name'];
  60. $newSearchPath = $searchPath . '/' . $prefix . $pkey;
  61. } else {
  62. $pkey = $key;
  63. $newSearchPath = $searchPath;
  64. }
  65. $result = $xml->xpath($newSearchPath);
  66. if ($result && is_array($result)) {
  67. foreach ($result as $subXml) {
  68. $subXml = simplexml_load_string($subXml->asXML());
  69. $subPrefix = $this->getXpathPrefix($subXml);
  70. $array[] = $this->parseXmlByType(
  71. '//' . $subPrefix . $pkey,
  72. $pkey,
  73. $items,
  74. $subXml,
  75. $subPrefix
  76. );
  77. }
  78. }
  79. return $array;
  80. } elseif ($type === 'object') {
  81. $properties = $value['properties'];
  82. $array = [];
  83. foreach ($properties as $pkey => $pvalue) {
  84. $name = isset($pvalue['sentAs']) ? $pvalue['sentAs'] : $pkey;
  85. $array[$pkey] = $this->parseXmlByType(
  86. $searchPath . '/' . $prefix . $name,
  87. $name,
  88. $pvalue,
  89. $xml,
  90. $prefix
  91. );
  92. }
  93. return $array;
  94. } else {
  95. // nothing handle
  96. }
  97. }
  98. if ($result = $xml->xpath($searchPath)) {
  99. if ($type === 'boolean') {
  100. return strval($result[0]) !== 'false';
  101. } elseif ($type === 'numeric' || $type === 'float') {
  102. return floatval($result[0]);
  103. } elseif ($type === 'int' || $type === 'integer') {
  104. return intval($result[0]);
  105. } else {
  106. return strval($result[0]);
  107. }
  108. } else {
  109. if ($type === 'boolean') {
  110. return false;
  111. } elseif ($type === 'numeric' || $type === 'float' || $type === 'int' || $type === 'integer') {
  112. return null;
  113. } else {
  114. return '';
  115. }
  116. }
  117. }
  118. private function isJsonResponse($response)
  119. {
  120. return $response->getHeaderLine('content-type') === 'application/json';
  121. }
  122. private function parseCommonHeaders($model, $response)
  123. {
  124. $constants = Constants::selectConstants($this->signature);
  125. foreach ($constants::COMMON_HEADERS as $key => $value) {
  126. $model[$value] = $response->getHeaderLine($key);
  127. }
  128. }
  129. protected function parseItems($responseParameters, $model, $response, $body)
  130. {
  131. $prefix = '';
  132. $this->parseCommonHeaders($model, $response);
  133. $closeBody = false;
  134. try {
  135. foreach ($responseParameters as $key => $value) {
  136. if (isset($value['location'])) {
  137. $location = $value['location'];
  138. if ($location === 'header') {
  139. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  140. $isSet = false;
  141. if (isset($value['type'])) {
  142. $type = $value['type'];
  143. if ($type === 'object') {
  144. $headers = $response->getHeaders();
  145. $temp = [];
  146. foreach ($headers as $headerName => $headerValue) {
  147. if (stripos($headerName, $name) === 0) {
  148. $metaKey = rawurldecode(substr($headerName, strlen($name)));
  149. $temp[$metaKey] = rawurldecode($response->getHeaderLine($headerName));
  150. }
  151. }
  152. $model[$key] = $temp;
  153. $isSet = true;
  154. } else {
  155. if ($response->hasHeader($name)) {
  156. if ($type === 'boolean') {
  157. $model[$key] = ($response->getHeaderLine($name)) !== 'false';
  158. $isSet = true;
  159. } elseif ($type === 'numeric' || $type === 'float') {
  160. $model[$key] = floatval($response->getHeaderLine($name));
  161. $isSet = true;
  162. } elseif ($type === 'int' || $type === 'integer') {
  163. $model[$key] = intval($response->getHeaderLine($name));
  164. $isSet = true;
  165. } else {
  166. // nothing handle
  167. }
  168. }
  169. }
  170. }
  171. if (!$isSet) {
  172. $model[$key] = rawurldecode($response->getHeaderLine($name));
  173. }
  174. } elseif ($location === 'xml' && $body !== null) {
  175. if (!isset($xml)) {
  176. $xml = simplexml_load_string($body->getContents());
  177. if ($xml) {
  178. $prefix = $this->getXpathPrefix($xml);
  179. }
  180. }
  181. $closeBody = true;
  182. $model[$key] = $this->parseXmlByType(null, $key, $value, $xml, $prefix);
  183. } elseif ($location === 'body' && $body !== null) {
  184. if (isset($value['type']) && $value['type'] === 'stream') {
  185. $model[$key] = $body;
  186. } elseif (isset($value['type']) && $value['type'] === 'json') {
  187. $jsonBody = trim($body->getContents());
  188. $data = json_decode($jsonBody, true);
  189. if ($jsonBody && $data) {
  190. if (is_array($data)) {
  191. $model[$key] = $data;
  192. } elseif (strlen($data)) {
  193. ObsLog::commonLog(
  194. ERROR,
  195. "response body %s, and jsonToArray data is %s",
  196. $body,
  197. $data
  198. );
  199. } else {
  200. // nothing handle
  201. }
  202. }
  203. $closeBody = true;
  204. } else {
  205. $model[$key] = $body->getContents();
  206. $closeBody = true;
  207. }
  208. } else {
  209. // nothing handle
  210. }
  211. }
  212. }
  213. } finally {
  214. if ($closeBody && $body !== null) {
  215. $body->close();
  216. }
  217. }
  218. }
  219. private function writeFile($filePath, StreamInterface &$body)
  220. {
  221. $filePath = iconv('UTF-8', 'GBK', $filePath);
  222. if (is_string($filePath) && $filePath !== '') {
  223. $fp = null;
  224. $dir = dirname($filePath);
  225. try {
  226. if (!is_dir($dir)) {
  227. mkdir($dir, 0755, true);
  228. }
  229. if ($fp = fopen($filePath, 'w')) {
  230. while (!$body->eof()) {
  231. $str = $body->read($this->chunkSize);
  232. fwrite($fp, $str);
  233. }
  234. fflush($fp);
  235. ObsLog::commonLog(DEBUG, "write file %s ok", $filePath);
  236. } else {
  237. ObsLog::commonLog(ERROR, "open file error,file path:%s", $filePath);
  238. }
  239. } finally {
  240. if ($fp) {
  241. fclose($fp);
  242. }
  243. $body->close();
  244. $body = null;
  245. }
  246. }
  247. }
  248. private function parseXmlToException($body, $obsException)
  249. {
  250. try {
  251. $xmlErrorBody = trim($body->getContents());
  252. if ($xmlErrorBody) {
  253. $xml = simplexml_load_string($xmlErrorBody);
  254. if ($xml) {
  255. $prefix = $this->getXpathPrefix($xml);
  256. if ($tempXml = $xml->xpath('//' . $prefix . 'Code')) {
  257. $obsException->setExceptionCode(strval($tempXml[0]));
  258. }
  259. if ($tempXml = $xml->xpath('//' . $prefix . 'RequestId')) {
  260. $obsException->setRequestId(strval($tempXml[0]));
  261. }
  262. if ($tempXml = $xml->xpath('//' . $prefix . 'Message')) {
  263. $obsException->setExceptionMessage(strval($tempXml[0]));
  264. }
  265. if ($tempXml = $xml->xpath('//' . $prefix . 'HostId')) {
  266. $obsException->setHostId(strval($tempXml[0]));
  267. }
  268. }
  269. }
  270. } finally {
  271. $body->close();
  272. }
  273. }
  274. private function parseJsonToException($body, $obsException)
  275. {
  276. try {
  277. $jsonErrorBody = trim($body->getContents());
  278. if ($jsonErrorBody) {
  279. $data = json_decode($jsonErrorBody, true);
  280. if ($data && is_array($data)) {
  281. if ($data['request_id']) {
  282. $obsException->setRequestId(strval($data['request_id']));
  283. }
  284. if ($data['code']) {
  285. $obsException->setExceptionCode(strval($data['code']));
  286. }
  287. if ($data['message']) {
  288. $obsException->setExceptionMessage(strval($data['message']));
  289. }
  290. } elseif ($data && strlen($data)) {
  291. ObsLog::commonLog(ERROR, "response body %s, and jsonToArray data is %s", $body, $data);
  292. $obsException->setExceptionMessage("Invalid response data,since it is not json data");
  293. } else {
  294. // nothing handle
  295. }
  296. }
  297. } finally {
  298. $body->close();
  299. }
  300. }
  301. private function parseJsonToModel($body, $model)
  302. {
  303. try {
  304. $jsonErrorBody = trim($body->getContents());
  305. if ($jsonErrorBody) {
  306. $jsonArray = json_decode($jsonErrorBody, true);
  307. if ($jsonArray && is_array($jsonArray)) {
  308. if ($jsonArray['request_id']) {
  309. $model['RequestId'] = strval($jsonArray['request_id']);
  310. }
  311. if ($jsonArray['code']) {
  312. $model['Code'] = strval($jsonArray['code']);
  313. }
  314. if ($jsonArray['message']) {
  315. $model['Message'] = strval($jsonArray['message']);
  316. }
  317. } elseif ($jsonArray && strlen($jsonArray)) {
  318. ObsLog::commonLog(ERROR, "response body %s, and jsonToArray data is %s", $body, $jsonArray);
  319. $model['Message'] = "Invalid response data,since it is not json data";
  320. } else {
  321. // nothing handle
  322. }
  323. }
  324. } finally {
  325. $body->close();
  326. }
  327. }
  328. private function parseXmlToModel($body, $model)
  329. {
  330. try {
  331. $xmlErrorBody = trim($body->getContents());
  332. $xml = simplexml_load_string($xmlErrorBody);
  333. if ($xmlErrorBody && $xml) {
  334. $prefix = $this->getXpathPrefix($xml);
  335. if ($tempXml = $xml->xpath('//' . $prefix . 'Code')) {
  336. $model['Code'] = strval($tempXml[0]);
  337. }
  338. if ($tempXml = $xml->xpath('//' . $prefix . 'RequestId')) {
  339. $model['RequestId'] = strval($tempXml[0]);
  340. }
  341. if ($tempXml = $xml->xpath('//' . $prefix . 'HostId')) {
  342. $model['HostId'] = strval($tempXml[0]);
  343. }
  344. if ($tempXml = $xml->xpath('//' . $prefix . 'Resource')) {
  345. $model['Resource'] = strval($tempXml[0]);
  346. }
  347. if ($tempXml = $xml->xpath('//' . $prefix . 'Message')) {
  348. $model['Message'] = strval($tempXml[0]);
  349. }
  350. }
  351. } finally {
  352. $body->close();
  353. }
  354. }
  355. protected function parseResponse(Model $model, Request $request, Response $response, array $requestConfig)
  356. {
  357. $statusCode = $response->getStatusCode();
  358. $expectedLength = $response->getHeaderLine('content-length');
  359. $responseContentType = $response->getHeaderLine('content-type');
  360. $expectedLength = is_numeric($expectedLength) ? floatval($expectedLength) : null;
  361. $body = new CheckoutStream($response->getBody(), $expectedLength);
  362. if ($statusCode >= 300) {
  363. if ($this->exceptionResponseMode) {
  364. $obsException = new ObsException();
  365. $obsException->setRequest($request);
  366. $obsException->setResponse($response);
  367. $obsException->setExceptionType($this->isClientError($response) ? 'client' : 'server');
  368. if ($responseContentType === 'application/json') {
  369. $this->parseJsonToException($body, $obsException);
  370. } else {
  371. $this->parseXmlToException($body, $obsException);
  372. }
  373. throw $obsException;
  374. } else {
  375. $this->parseCommonHeaders($model, $response);
  376. if ($responseContentType === 'application/json') {
  377. $this->parseJsonToModel($body, $model);
  378. } else {
  379. $this->parseXmlToModel($body, $model);
  380. }
  381. }
  382. } else {
  383. if (!empty($model)) {
  384. foreach ($model as $key => $value) {
  385. if ($key === 'method') {
  386. continue;
  387. }
  388. if (isset($value['type']) && $value['type'] === 'file') {
  389. $this->writeFile($value['value'], $body);
  390. }
  391. $model[$key] = $value['value'];
  392. }
  393. }
  394. if (isset($requestConfig['responseParameters'])) {
  395. $responseParameters = $requestConfig['responseParameters'];
  396. if (isset($responseParameters['type']) && $responseParameters['type'] === 'object') {
  397. $responseParameters = $responseParameters['properties'];
  398. }
  399. $this->parseItems($responseParameters, $model, $response, $body);
  400. }
  401. }
  402. $model['HttpStatusCode'] = $statusCode;
  403. $model['Reason'] = $response->getReasonPhrase();
  404. }
  405. protected function getXpathPrefix($xml)
  406. {
  407. $namespaces = $xml->getDocNamespaces();
  408. if (isset($namespaces[''])) {
  409. $xml->registerXPathNamespace('ns', $namespaces['']);
  410. $prefix = 'ns:';
  411. } else {
  412. $prefix = '';
  413. }
  414. return $prefix;
  415. }
  416. protected function buildException(Request $request, RequestException $exception, $message)
  417. {
  418. $response = $exception->hasResponse() ? $exception->getResponse() : null;
  419. $obsException = new ObsException($message ? $message : $exception->getMessage());
  420. $obsException->setExceptionType('client');
  421. $obsException->setRequest($request);
  422. if ($response) {
  423. $obsException->setResponse($response);
  424. $obsException->setExceptionType($this->isClientError($response) ? 'client' : 'server');
  425. if ($this->isJsonResponse($response)) {
  426. $this->parseJsonToException($response->getBody(), $obsException);
  427. } else {
  428. $this->parseXmlToException($response->getBody(), $obsException);
  429. }
  430. if ($obsException->getRequestId() === null) {
  431. $prefix = strcasecmp($this->signature, 'obs') === 0 ? 'x-obs-' : 'x-amz-';
  432. $requestId = $response->getHeaderLine($prefix . 'request-id');
  433. $obsException->setRequestId($requestId);
  434. }
  435. }
  436. return $obsException;
  437. }
  438. protected function parseExceptionAsync(Request $request, RequestException $exception, $message = null)
  439. {
  440. return $this->buildException($request, $exception, $message);
  441. }
  442. protected function parseException(Model $model, Request $request, RequestException $exception, $message = null)
  443. {
  444. $response = $exception->hasResponse() ? $exception->getResponse() : null;
  445. if ($this->exceptionResponseMode) {
  446. throw $this->buildException($request, $exception, $message);
  447. } else {
  448. if ($response) {
  449. $model['HttpStatusCode'] = $response->getStatusCode();
  450. $model['Reason'] = $response->getReasonPhrase();
  451. $this->parseXmlToModel($response->getBody(), $model);
  452. } else {
  453. $model['HttpStatusCode'] = -1;
  454. $model['Message'] = $exception->getMessage();
  455. }
  456. }
  457. }
  458. }