GetResponseTrait.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 parseCommonHeaders($model, $response){
  106. $constants = Constants::selectConstants($this -> signature);
  107. foreach($constants::COMMON_HEADERS as $key => $value){
  108. $model[$value] = $response -> getHeaderLine($key);
  109. }
  110. }
  111. protected function parseItems($responseParameters, $model, $response, $body)
  112. {
  113. $prefix = '';
  114. $this->parseCommonHeaders($model, $response);
  115. $closeBody = false;
  116. try{
  117. foreach ($responseParameters as $key => $value){
  118. if(isset($value['location'])){
  119. $location = $value['location'];
  120. if($location === 'header'){
  121. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  122. $isSet = false;
  123. if(isset($value['type'])){
  124. $type = $value['type'];
  125. if($type === 'object'){
  126. $headers = $response -> getHeaders();
  127. $temp = [];
  128. foreach ($headers as $headerName => $headerValue){
  129. if(stripos($headerName, $name) === 0){
  130. $metaKey = rawurldecode(substr($headerName, strlen($name)));
  131. $temp[$metaKey] = rawurldecode($response -> getHeaderLine($headerName));
  132. }
  133. }
  134. $model[$key] = $temp;
  135. $isSet = true;
  136. }else{
  137. if($response -> hasHeader($name)){
  138. if($type === 'boolean'){
  139. $model[$key] = ($response -> getHeaderLine($name)) !== 'false';
  140. $isSet = true;
  141. }else if($type === 'numeric' || $type === 'float'){
  142. $model[$key] = floatval($response -> getHeaderLine($name));
  143. $isSet = true;
  144. }else if($type === 'int' || $type === 'integer'){
  145. $model[$key] = intval($response -> getHeaderLine($name));
  146. $isSet = true;
  147. }
  148. }
  149. }
  150. }
  151. if(!$isSet){
  152. $model[$key] = rawurldecode($response -> getHeaderLine($name));
  153. }
  154. }else if($location === 'xml' && $body !== null){
  155. if(!isset($xml) && ($xml = simplexml_load_string($body -> getContents()))){
  156. $prefix = $this ->getXpathPrefix($xml);
  157. }
  158. $closeBody = true;
  159. $model[$key] = $this -> parseXmlByType(null, $key,$value, $xml, $prefix);
  160. }else if($location === 'body' && $body !== null){
  161. if(isset($value['type']) && $value['type'] === 'stream'){
  162. $model[$key] = $body;
  163. }else{
  164. $model[$key] = $body -> getContents();
  165. $closeBody = true;
  166. }
  167. }
  168. }
  169. }
  170. }finally {
  171. if($closeBody && $body !== null){
  172. $body -> close();
  173. }
  174. }
  175. }
  176. private function writeFile($filePath, StreamInterface &$body, $contentLength)
  177. {
  178. $filePath = iconv('UTF-8', 'GBK', $filePath);
  179. if(is_string($filePath) && $filePath !== '')
  180. {
  181. $fp = null;
  182. $dir = dirname($filePath);
  183. try{
  184. if(!is_dir($dir))
  185. {
  186. mkdir($dir,0755,true);
  187. }
  188. if(($fp = fopen($filePath, 'w')))
  189. {
  190. while(!$body->eof())
  191. {
  192. $str = $body->read($this->chunkSize);
  193. fwrite($fp, $str);
  194. }
  195. fflush($fp);
  196. ObsLog::commonLog(DEBUG, "write file %s ok",$filePath);
  197. }
  198. else{
  199. ObsLog::commonLog(ERROR, "open file error,file path:%s",$filePath);
  200. }
  201. }finally{
  202. if($fp){
  203. fclose($fp);
  204. }
  205. $body->close();
  206. $body = null;
  207. }
  208. }
  209. }
  210. private function parseXmlToException($body, $obsException){
  211. try{
  212. $xmlErrorBody = trim($body -> getContents());
  213. if($xmlErrorBody && ($xml = simplexml_load_string($xmlErrorBody))){
  214. $prefix = $this->getXpathPrefix($xml);
  215. if ($tempXml = $xml->xpath('//'.$prefix . 'Code')) {
  216. $obsException-> setExceptionCode(strval($tempXml[0]));
  217. }
  218. if ($tempXml = $xml->xpath('//'.$prefix . 'RequestId')) {
  219. $obsException-> setRequestId(strval($tempXml[0]));
  220. }
  221. if ($tempXml = $xml->xpath('//'.$prefix . 'Message')) {
  222. $obsException-> setExceptionMessage(strval($tempXml[0]));
  223. }
  224. if ($tempXml = $xml->xpath('//'.$prefix . 'HostId')) {
  225. $obsException -> setHostId(strval($tempXml[0]));
  226. }
  227. }
  228. }finally{
  229. $body -> close();
  230. }
  231. }
  232. private function parseXmlToModel($body, $model){
  233. try{
  234. $xmlErrorBody = trim($body -> getContents());
  235. if($xmlErrorBody && ($xml = simplexml_load_string($xmlErrorBody))){
  236. $prefix = $this->getXpathPrefix($xml);
  237. if ($tempXml = $xml->xpath('//'.$prefix . 'Code')) {
  238. $model['Code'] = strval($tempXml[0]);
  239. }
  240. if ($tempXml = $xml->xpath('//'.$prefix . 'RequestId')) {
  241. $model['RequestId'] = strval($tempXml[0]);
  242. }
  243. if ($tempXml = $xml->xpath('//'.$prefix . 'HostId')) {
  244. $model['HostId'] = strval($tempXml[0]);
  245. }
  246. if ($tempXml = $xml->xpath('//'.$prefix . 'Resource')) {
  247. $model['Resource'] = strval($tempXml[0]);
  248. }
  249. if ($tempXml = $xml->xpath('//'.$prefix . 'Message')) {
  250. $model['Message'] = strval($tempXml[0]);
  251. }
  252. }
  253. }finally {
  254. $body -> close();
  255. }
  256. }
  257. protected function parseResponse(Model $model, Request $request, Response $response, array $requestConfig)
  258. {
  259. $statusCode = $response -> getStatusCode();
  260. $expectedLength = $response -> getHeaderLine('content-length');
  261. $expectedLength = is_numeric($expectedLength) ? floatval($expectedLength) : null;
  262. $body = new CheckoutStream($response->getBody(), $expectedLength);
  263. if($statusCode >= 300){
  264. if($this-> exceptionResponseMode){
  265. $obsException= new ObsException();
  266. $obsException-> setRequest($request);
  267. $obsException-> setResponse($response);
  268. $obsException-> setExceptionType($this->isClientError($response) ? 'client' : 'server');
  269. $this->parseXmlToException($body, $obsException);
  270. throw $obsException;
  271. }else{
  272. $this->parseCommonHeaders($model, $response);
  273. $this->parseXmlToModel($body, $model);
  274. }
  275. }else{
  276. if(!empty($model)){
  277. foreach ($model as $key => $value){
  278. if($key === 'method'){
  279. continue;
  280. }
  281. if(isset($value['type']) && $value['type'] === 'file'){
  282. $this->writeFile($value['value'], $body, $expectedLength);
  283. }
  284. $model[$key] = $value['value'];
  285. }
  286. }
  287. if(isset($requestConfig['responseParameters'])){
  288. $responseParameters = $requestConfig['responseParameters'];
  289. if(isset($responseParameters['type']) && $responseParameters['type'] === 'object'){
  290. $responseParameters = $responseParameters['properties'];
  291. }
  292. $this->parseItems($responseParameters, $model, $response, $body);
  293. }
  294. }
  295. $model['HttpStatusCode'] = $statusCode;
  296. $model['Reason'] = $response -> getReasonPhrase();
  297. }
  298. protected function getXpathPrefix($xml)
  299. {
  300. $namespaces = $xml -> getDocNamespaces();
  301. if (isset($namespaces[''])) {
  302. $xml->registerXPathNamespace('ns', $namespaces['']);
  303. $prefix = 'ns:';
  304. } else {
  305. $prefix = '';
  306. }
  307. return $prefix;
  308. }
  309. protected function buildException(Request $request, RequestException $exception, $message)
  310. {
  311. $response = $exception-> hasResponse() ? $exception-> getResponse() : null;
  312. $obsException= new ObsException($message ? $message : $exception-> getMessage());
  313. $obsException-> setExceptionType('client');
  314. $obsException-> setRequest($request);
  315. if($response){
  316. $obsException-> setResponse($response);
  317. $obsException-> setExceptionType($this->isClientError($response) ? 'client' : 'server');
  318. $this->parseXmlToException($response -> getBody(), $obsException);
  319. if ($obsException->getRequestId() === null) {
  320. $prefix = strcasecmp($this->signature, 'obs' ) === 0 ? 'x-obs-' : 'x-amz-';
  321. $requestId = $response->getHeaderLine($prefix . 'request-id');
  322. $obsException->setRequestId($requestId);
  323. }
  324. }
  325. return $obsException;
  326. }
  327. protected function parseExceptionAsync(Request $request, RequestException $exception, $message=null)
  328. {
  329. return $this->buildException($request, $exception, $message);
  330. }
  331. protected function parseException(Model $model, Request $request, RequestException $exception, $message=null)
  332. {
  333. $response = $exception-> hasResponse() ? $exception-> getResponse() : null;
  334. if($this-> exceptionResponseMode){
  335. throw $this->buildException($request, $exception, $message);
  336. }else{
  337. if($response){
  338. $model['HttpStatusCode'] = $response -> getStatusCode();
  339. $model['Reason'] = $response -> getReasonPhrase();
  340. $this->parseXmlToModel($response -> getBody(), $model);
  341. }else{
  342. $model['HttpStatusCode'] = -1;
  343. $model['Message'] = $exception -> getMessage();
  344. }
  345. }
  346. }
  347. }