GetResponseTrait.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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\Psr7\Request;
  18. use GuzzleHttp\Psr7\Response;
  19. use GuzzleHttp\Exception\RequestException;
  20. use Obs\ObsException;
  21. use Obs\Internal\Common\Model;
  22. use Obs\Internal\Resource\Constants;
  23. use Obs\Log\ObsLog;
  24. use Psr\Http\Message\StreamInterface;
  25. use Obs\Internal\Common\CheckoutStream;
  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. $_searchPath = $searchPath .'/' . $prefix .$pkey;
  61. }else{
  62. $pkey = $key;
  63. $_searchPath = $searchPath;
  64. }
  65. if($result = $xml -> xpath($_searchPath)){
  66. if(is_array($result)){
  67. foreach ($result as $subXml){
  68. $subXml = simplexml_load_string($subXml -> asXML());
  69. $subPrefix = $this->getXpathPrefix($subXml);
  70. $array[] = $this->parseXmlByType('//'.$subPrefix. $pkey, $pkey, $items, $subXml, $subPrefix);
  71. }
  72. }
  73. }
  74. return $array;
  75. }else if($type === 'object'){
  76. $properties = $value['properties'];
  77. $array = [];
  78. foreach ($properties as $pkey => $pvalue){
  79. $name = isset($pvalue['sentAs']) ? $pvalue['sentAs'] : $pkey;
  80. $array[$pkey] = $this->parseXmlByType($searchPath.'/' . $prefix .$name, $name, $pvalue, $xml, $prefix);
  81. }
  82. return $array;
  83. }
  84. }
  85. if($result = $xml -> xpath($searchPath)){
  86. if($type === 'boolean'){
  87. return strval($result[0]) !== 'false';
  88. }else if($type === 'numeric' || $type === 'float'){
  89. return floatval($result[0]);
  90. }else if($type === 'int' || $type === 'integer'){
  91. return intval($result[0]);
  92. }else{
  93. return strval($result[0]);
  94. }
  95. }else{
  96. if($type === 'boolean'){
  97. return false;
  98. }else if($type === 'numeric' || $type === 'float' || $type === 'int' || $type === 'integer'){
  99. return null;
  100. }else{
  101. return '';
  102. }
  103. }
  104. }
  105. private function isJsonResponse($response) {
  106. return $response -> getHeaderLine('content-type') === 'application/json';
  107. }
  108. private function parseCommonHeaders($model, $response){
  109. $constants = Constants::selectConstants($this -> signature);
  110. foreach($constants::COMMON_HEADERS as $key => $value){
  111. $model[$value] = $response -> getHeaderLine($key);
  112. }
  113. }
  114. protected function parseItems($responseParameters, $model, $response, $body)
  115. {
  116. $prefix = '';
  117. $this->parseCommonHeaders($model, $response);
  118. $closeBody = false;
  119. try{
  120. foreach ($responseParameters as $key => $value){
  121. if(isset($value['location'])){
  122. $location = $value['location'];
  123. if($location === 'header'){
  124. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  125. $isSet = false;
  126. if(isset($value['type'])){
  127. $type = $value['type'];
  128. if($type === 'object'){
  129. $headers = $response -> getHeaders();
  130. $temp = [];
  131. foreach ($headers as $headerName => $headerValue){
  132. if(stripos($headerName, $name) === 0){
  133. $metaKey = rawurldecode(substr($headerName, strlen($name)));
  134. $temp[$metaKey] = rawurldecode($response -> getHeaderLine($headerName));
  135. }
  136. }
  137. $model[$key] = $temp;
  138. $isSet = true;
  139. }else{
  140. if($response -> hasHeader($name)){
  141. if($type === 'boolean'){
  142. $model[$key] = ($response -> getHeaderLine($name)) !== 'false';
  143. $isSet = true;
  144. }else if($type === 'numeric' || $type === 'float'){
  145. $model[$key] = floatval($response -> getHeaderLine($name));
  146. $isSet = true;
  147. }else if($type === 'int' || $type === 'integer'){
  148. $model[$key] = intval($response -> getHeaderLine($name));
  149. $isSet = true;
  150. }
  151. }
  152. }
  153. }
  154. if(!$isSet){
  155. $model[$key] = rawurldecode($response -> getHeaderLine($name));
  156. }
  157. }else if($location === 'xml' && $body !== null){
  158. if(!isset($xml) && ($xml = simplexml_load_string($body -> getContents()))){
  159. $prefix = $this ->getXpathPrefix($xml);
  160. }
  161. $closeBody = true;
  162. $model[$key] = $this -> parseXmlByType(null, $key,$value, $xml, $prefix);
  163. }else if($location === 'body' && $body !== null){
  164. if(isset($value['type']) && $value['type'] === 'stream'){
  165. $model[$key] = $body;
  166. }else if (isset($value['type']) && $value['type'] === 'json') {
  167. $jsonBody = trim($body -> getContents());
  168. if ($jsonBody && ($data = json_decode($jsonBody, true))) {
  169. if (is_array($data)) {
  170. $model[$key] = $data;
  171. } elseif (strlen($data)) {
  172. ObsLog::commonLog(ERROR, "response body %s, and jsonToArray data is %s",$body, $data);
  173. }
  174. }
  175. $closeBody = true;
  176. } else {
  177. $model[$key] = $body -> getContents();
  178. $closeBody = true;
  179. }
  180. }
  181. }
  182. }
  183. }finally {
  184. if($closeBody && $body !== null){
  185. $body -> close();
  186. }
  187. }
  188. }
  189. private function writeFile($filePath, StreamInterface &$body, $contentLength)
  190. {
  191. $filePath = iconv('UTF-8', 'GBK', $filePath);
  192. if(is_string($filePath) && $filePath !== '')
  193. {
  194. $fp = null;
  195. $dir = dirname($filePath);
  196. try{
  197. if(!is_dir($dir))
  198. {
  199. mkdir($dir,0755,true);
  200. }
  201. if(($fp = fopen($filePath, 'w')))
  202. {
  203. while(!$body->eof())
  204. {
  205. $str = $body->read($this->chunkSize);
  206. fwrite($fp, $str);
  207. }
  208. fflush($fp);
  209. ObsLog::commonLog(DEBUG, "write file %s ok",$filePath);
  210. }
  211. else{
  212. ObsLog::commonLog(ERROR, "open file error,file path:%s",$filePath);
  213. }
  214. }finally{
  215. if($fp){
  216. fclose($fp);
  217. }
  218. $body->close();
  219. $body = null;
  220. }
  221. }
  222. }
  223. private function parseXmlToException($body, $obsException){
  224. try{
  225. $xmlErrorBody = trim($body -> getContents());
  226. if($xmlErrorBody && ($xml = simplexml_load_string($xmlErrorBody))){
  227. $prefix = $this->getXpathPrefix($xml);
  228. if ($tempXml = $xml->xpath('//'.$prefix . 'Code')) {
  229. $obsException-> setExceptionCode(strval($tempXml[0]));
  230. }
  231. if ($tempXml = $xml->xpath('//'.$prefix . 'RequestId')) {
  232. $obsException-> setRequestId(strval($tempXml[0]));
  233. }
  234. if ($tempXml = $xml->xpath('//'.$prefix . 'Message')) {
  235. $obsException-> setExceptionMessage(strval($tempXml[0]));
  236. }
  237. if ($tempXml = $xml->xpath('//'.$prefix . 'HostId')) {
  238. $obsException -> setHostId(strval($tempXml[0]));
  239. }
  240. }
  241. }finally{
  242. $body -> close();
  243. }
  244. }
  245. private function parseJsonToException($body, $obsException) {
  246. try {
  247. $jsonErrorBody = trim($body -> getContents());
  248. if ($jsonErrorBody && ($data = json_decode($jsonErrorBody, true))) {
  249. if (is_array($data)) {
  250. if ($data['request_id']) {
  251. $obsException -> setRequestId(strval($data['request_id']));
  252. }
  253. if ($data['code']) {
  254. $obsException -> setExceptionCode(strval($data['code']));
  255. }
  256. if ($data['message']) {
  257. $obsException -> setExceptionMessage(strval($data['message']));
  258. }
  259. } elseif (strlen($data)) {
  260. ObsLog::commonLog(ERROR, "response body %s, and jsonToArray data is %s",$body, $data);
  261. $obsException-> setExceptionMessage("Invalid response data,since it is not json data");
  262. }
  263. }
  264. } finally {
  265. $body -> close();
  266. }
  267. }
  268. private function parseJsonToModel($body, $model) {
  269. try{
  270. $jsonErrorBody = trim($body -> getContents());
  271. if ($jsonErrorBody && ($jsonArray = json_decode($jsonErrorBody, true))) {
  272. if (is_array($jsonArray)) {
  273. if ($jsonArray['request_id']) {
  274. $model['RequestId'] = strval($jsonArray['request_id']);
  275. }
  276. if ($jsonArray['code']) {
  277. $model['Code'] = strval($jsonArray['code']);
  278. }
  279. if ($jsonArray['message']) {
  280. $model['Message'] = strval($jsonArray['message']);
  281. }
  282. } elseif (strlen($jsonArray)) {
  283. ObsLog::commonLog(ERROR, "response body %s, and jsonToArray data is %s",$body, $jsonArray);
  284. $model['Message'] = "Invalid response data,since it is not json data";
  285. }
  286. }
  287. } finally {
  288. $body -> close();
  289. }
  290. }
  291. private function parseXmlToModel($body, $model){
  292. try{
  293. $xmlErrorBody = trim($body -> getContents());
  294. if($xmlErrorBody && ($xml = simplexml_load_string($xmlErrorBody))){
  295. $prefix = $this->getXpathPrefix($xml);
  296. if ($tempXml = $xml->xpath('//'.$prefix . 'Code')) {
  297. $model['Code'] = strval($tempXml[0]);
  298. }
  299. if ($tempXml = $xml->xpath('//'.$prefix . 'RequestId')) {
  300. $model['RequestId'] = strval($tempXml[0]);
  301. }
  302. if ($tempXml = $xml->xpath('//'.$prefix . 'HostId')) {
  303. $model['HostId'] = strval($tempXml[0]);
  304. }
  305. if ($tempXml = $xml->xpath('//'.$prefix . 'Resource')) {
  306. $model['Resource'] = strval($tempXml[0]);
  307. }
  308. if ($tempXml = $xml->xpath('//'.$prefix . 'Message')) {
  309. $model['Message'] = strval($tempXml[0]);
  310. }
  311. }
  312. }finally {
  313. $body -> close();
  314. }
  315. }
  316. protected function parseResponse(Model $model, Request $request, Response $response, array $requestConfig)
  317. {
  318. $statusCode = $response -> getStatusCode();
  319. $expectedLength = $response -> getHeaderLine('content-length');
  320. $responseContentType = $response -> getHeaderLine('content-type');
  321. $expectedLength = is_numeric($expectedLength) ? floatval($expectedLength) : null;
  322. $body = new CheckoutStream($response->getBody(), $expectedLength);
  323. if($statusCode >= 300){
  324. if($this-> exceptionResponseMode){
  325. $obsException= new ObsException();
  326. $obsException-> setRequest($request);
  327. $obsException-> setResponse($response);
  328. $obsException-> setExceptionType($this->isClientError($response) ? 'client' : 'server');
  329. if ($responseContentType === 'application/json') {
  330. $this->parseJsonToException($body, $obsException);
  331. } else {
  332. $this->parseXmlToException($body, $obsException);
  333. }
  334. throw $obsException;
  335. }else{
  336. $this->parseCommonHeaders($model, $response);
  337. if ($responseContentType === 'application/json') {
  338. $this->parseJsonToModel($body, $model);
  339. } else {
  340. $this->parseXmlToModel($body, $model);
  341. }
  342. }
  343. }else{
  344. if(!empty($model)){
  345. foreach ($model as $key => $value){
  346. if($key === 'method'){
  347. continue;
  348. }
  349. if(isset($value['type']) && $value['type'] === 'file'){
  350. $this->writeFile($value['value'], $body, $expectedLength);
  351. }
  352. $model[$key] = $value['value'];
  353. }
  354. }
  355. if(isset($requestConfig['responseParameters'])){
  356. $responseParameters = $requestConfig['responseParameters'];
  357. if(isset($responseParameters['type']) && $responseParameters['type'] === 'object'){
  358. $responseParameters = $responseParameters['properties'];
  359. }
  360. $this->parseItems($responseParameters, $model, $response, $body);
  361. }
  362. }
  363. $model['HttpStatusCode'] = $statusCode;
  364. $model['Reason'] = $response -> getReasonPhrase();
  365. }
  366. protected function getXpathPrefix($xml)
  367. {
  368. $namespaces = $xml -> getDocNamespaces();
  369. if (isset($namespaces[''])) {
  370. $xml->registerXPathNamespace('ns', $namespaces['']);
  371. $prefix = 'ns:';
  372. } else {
  373. $prefix = '';
  374. }
  375. return $prefix;
  376. }
  377. protected function buildException(Request $request, RequestException $exception, $message)
  378. {
  379. $response = $exception-> hasResponse() ? $exception-> getResponse() : null;
  380. $obsException= new ObsException($message ? $message : $exception-> getMessage());
  381. $obsException-> setExceptionType('client');
  382. $obsException-> setRequest($request);
  383. if($response){
  384. $obsException-> setResponse($response);
  385. $obsException-> setExceptionType($this->isClientError($response) ? 'client' : 'server');
  386. if ($this->isJsonResponse($response)) {
  387. $this->parseJsonToException($response -> getBody(), $obsException);
  388. } else {
  389. $this->parseXmlToException($response -> getBody(), $obsException);
  390. }
  391. if ($obsException->getRequestId() === null) {
  392. $prefix = strcasecmp($this->signature, 'obs' ) === 0 ? 'x-obs-' : 'x-amz-';
  393. $requestId = $response->getHeaderLine($prefix . 'request-id');
  394. $obsException->setRequestId($requestId);
  395. }
  396. }
  397. return $obsException;
  398. }
  399. protected function parseExceptionAsync(Request $request, RequestException $exception, $message=null)
  400. {
  401. return $this->buildException($request, $exception, $message);
  402. }
  403. protected function parseException(Model $model, Request $request, RequestException $exception, $message=null)
  404. {
  405. $response = $exception-> hasResponse() ? $exception-> getResponse() : null;
  406. if($this-> exceptionResponseMode){
  407. throw $this->buildException($request, $exception, $message);
  408. }else{
  409. if($response){
  410. $model['HttpStatusCode'] = $response -> getStatusCode();
  411. $model['Reason'] = $response -> getReasonPhrase();
  412. $this->parseXmlToModel($response -> getBody(), $model);
  413. }else{
  414. $model['HttpStatusCode'] = -1;
  415. $model['Message'] = $exception -> getMessage();
  416. }
  417. }
  418. }
  419. }