Няма описание

Client.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. namespace GuzzleHttp;
  3. use GuzzleHttp\Cookie\CookieJar;
  4. use GuzzleHttp\Promise;
  5. use GuzzleHttp\Psr7;
  6. use Psr\Http\Message\UriInterface;
  7. use Psr\Http\Message\RequestInterface;
  8. use Psr\Http\Message\ResponseInterface;
  9. require __DIR__.'/Psr7/functions.php';
  10. require __DIR__.'/Promise/functions.php';
  11. /**
  12. * @method ResponseInterface get($uri, array $options = [])
  13. * @method ResponseInterface head($uri, array $options = [])
  14. * @method ResponseInterface put($uri, array $options = [])
  15. * @method ResponseInterface post($uri, array $options = [])
  16. * @method ResponseInterface patch($uri, array $options = [])
  17. * @method ResponseInterface delete($uri, array $options = [])
  18. * @method Promise\PromiseInterface getAsync($uri, array $options = [])
  19. * @method Promise\PromiseInterface headAsync($uri, array $options = [])
  20. * @method Promise\PromiseInterface putAsync($uri, array $options = [])
  21. * @method Promise\PromiseInterface postAsync($uri, array $options = [])
  22. * @method Promise\PromiseInterface patchAsync($uri, array $options = [])
  23. * @method Promise\PromiseInterface deleteAsync($uri, array $options = [])
  24. */
  25. class Client implements ClientInterface
  26. {
  27. /** @var array Default request options */
  28. private $config;
  29. /**
  30. * Clients accept an array of constructor parameters.
  31. *
  32. * Here's an example of creating a client using a base_uri and an array of
  33. * default request options to apply to each request:
  34. *
  35. * $client = new Client([
  36. * 'base_uri' => 'http://www.foo.com/1.0/',
  37. * 'timeout' => 0,
  38. * 'allow_redirects' => false,
  39. * 'proxy' => '192.168.16.1:10'
  40. * ]);
  41. *
  42. * Client configuration settings include the following options:
  43. *
  44. * - handler: (callable) Function that transfers HTTP requests over the
  45. * wire. The function is called with a Psr7\Http\Message\RequestInterface
  46. * and array of transfer options, and must return a
  47. * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
  48. * Psr7\Http\Message\ResponseInterface on success. "handler" is a
  49. * constructor only option that cannot be overridden in per/request
  50. * options. If no handler is provided, a default handler will be created
  51. * that enables all of the request options below by attaching all of the
  52. * default middleware to the handler.
  53. * - base_uri: (string|UriInterface) Base URI of the client that is merged
  54. * into relative URIs. Can be a string or instance of UriInterface.
  55. * - **: any request option
  56. *
  57. * @param array $config Client configuration settings.
  58. *
  59. * @see \GuzzleHttp\RequestOptions for a list of available request options.
  60. */
  61. public function __construct(array $config = [])
  62. {
  63. if (!isset($config['handler'])) {
  64. $config['handler'] = HandlerStack::create();
  65. }
  66. // Convert the base_uri to a UriInterface
  67. if (isset($config['base_uri'])) {
  68. $config['base_uri'] = Psr7\uri_for($config['base_uri']);
  69. }
  70. $this->configureDefaults($config);
  71. }
  72. public function __call($method, $args)
  73. {
  74. if (count($args) < 1) {
  75. throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
  76. }
  77. $uri = $args[0];
  78. $opts = isset($args[1]) ? $args[1] : [];
  79. return substr($method, -5) === 'Async'
  80. ? $this->requestAsync(substr($method, 0, -5), $uri, $opts)
  81. : $this->request($method, $uri, $opts);
  82. }
  83. public function sendAsync(RequestInterface $request, array $options = [])
  84. {
  85. // Merge the base URI into the request URI if needed.
  86. $options = $this->prepareDefaults($options);
  87. return $this->transfer(
  88. $request->withUri($this->buildUri($request->getUri(), $options)),
  89. $options
  90. );
  91. }
  92. public function send(RequestInterface $request, array $options = [])
  93. {
  94. $options[RequestOptions::SYNCHRONOUS] = true;
  95. return $this->sendAsync($request, $options)->wait();
  96. }
  97. public function requestAsync($method, $uri = null, array $options = [])
  98. {
  99. $options = $this->prepareDefaults($options);
  100. // Remove request modifying parameter because it can be done up-front.
  101. $headers = isset($options['headers']) ? $options['headers'] : [];
  102. $body = isset($options['body']) ? $options['body'] : null;
  103. $version = isset($options['version']) ? $options['version'] : '1.1';
  104. // Merge the URI into the base URI.
  105. $uri = $this->buildUri($uri, $options);
  106. if (is_array($body)) {
  107. $this->invalidBody();
  108. }
  109. $request = new Psr7\Request($method, $uri, $headers, $body, $version);
  110. // Remove the option so that they are not doubly-applied.
  111. unset($options['headers'], $options['body'], $options['version']);
  112. return $this->transfer($request, $options);
  113. }
  114. public function request($method, $uri = null, array $options = [])
  115. {
  116. $options[RequestOptions::SYNCHRONOUS] = true;
  117. return $this->requestAsync($method, $uri, $options)->wait();
  118. }
  119. public function getConfig($option = null)
  120. {
  121. return $option === null
  122. ? $this->config
  123. : (isset($this->config[$option]) ? $this->config[$option] : null);
  124. }
  125. private function buildUri($uri, array $config)
  126. {
  127. if (!isset($config['base_uri'])) {
  128. return $uri instanceof UriInterface ? $uri : new Psr7\Uri($uri);
  129. }
  130. return Psr7\Uri::resolve(Psr7\uri_for($config['base_uri']), $uri);
  131. }
  132. /**
  133. * Configures the default options for a client.
  134. *
  135. * @param array $config
  136. */
  137. private function configureDefaults(array $config)
  138. {
  139. $defaults = [
  140. 'allow_redirects' => RedirectMiddleware::$defaultSettings,
  141. 'http_errors' => true,
  142. 'decode_content' => true,
  143. 'verify' => true,
  144. 'cookies' => false
  145. ];
  146. // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set
  147. if ($proxy = getenv('HTTP_PROXY')) {
  148. $defaults['proxy']['http'] = $proxy;
  149. }
  150. if ($proxy = getenv('HTTPS_PROXY')) {
  151. $defaults['proxy']['https'] = $proxy;
  152. }
  153. if ($noProxy = getenv('NO_PROXY')) {
  154. $cleanedNoProxy = str_replace(' ', '', $noProxy);
  155. $defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
  156. }
  157. $this->config = $config + $defaults;
  158. if (!empty($config['cookies']) && $config['cookies'] === true) {
  159. $this->config['cookies'] = new CookieJar();
  160. }
  161. // Add the default user-agent header.
  162. if (!isset($this->config['headers'])) {
  163. $this->config['headers'] = ['User-Agent' => default_user_agent()];
  164. } else {
  165. // Add the User-Agent header if one was not already set.
  166. foreach (array_keys($this->config['headers']) as $name) {
  167. if (strtolower($name) === 'user-agent') {
  168. return;
  169. }
  170. }
  171. $this->config['headers']['User-Agent'] = default_user_agent();
  172. }
  173. }
  174. /**
  175. * Merges default options into the array.
  176. *
  177. * @param array $options Options to modify by reference
  178. *
  179. * @return array
  180. */
  181. private function prepareDefaults($options)
  182. {
  183. $defaults = $this->config;
  184. if (!empty($defaults['headers'])) {
  185. // Default headers are only added if they are not present.
  186. $defaults['_conditional'] = $defaults['headers'];
  187. unset($defaults['headers']);
  188. }
  189. // Special handling for headers is required as they are added as
  190. // conditional headers and as headers passed to a request ctor.
  191. if (array_key_exists('headers', $options)) {
  192. // Allows default headers to be unset.
  193. if ($options['headers'] === null) {
  194. $defaults['_conditional'] = null;
  195. unset($options['headers']);
  196. } elseif (!is_array($options['headers'])) {
  197. throw new \InvalidArgumentException('headers must be an array');
  198. }
  199. }
  200. // Shallow merge defaults underneath options.
  201. $result = $options + $defaults;
  202. // Remove null values.
  203. foreach ($result as $k => $v) {
  204. if ($v === null) {
  205. unset($result[$k]);
  206. }
  207. }
  208. return $result;
  209. }
  210. /**
  211. * Transfers the given request and applies request options.
  212. *
  213. * The URI of the request is not modified and the request options are used
  214. * as-is without merging in default options.
  215. *
  216. * @param RequestInterface $request
  217. * @param array $options
  218. *
  219. * @return Promise\PromiseInterface
  220. */
  221. private function transfer(RequestInterface $request, array $options)
  222. {
  223. // save_to -> sink
  224. if (isset($options['save_to'])) {
  225. $options['sink'] = $options['save_to'];
  226. unset($options['save_to']);
  227. }
  228. // exceptions -> http_error
  229. if (isset($options['exceptions'])) {
  230. $options['http_errors'] = $options['exceptions'];
  231. unset($options['exceptions']);
  232. }
  233. $request = $this->applyOptions($request, $options);
  234. $handler = $options['handler'];
  235. try {
  236. return Promise\promise_for($handler($request, $options));
  237. } catch (\Exception $e) {
  238. return Promise\rejection_for($e);
  239. }
  240. }
  241. /**
  242. * Applies the array of request options to a request.
  243. *
  244. * @param RequestInterface $request
  245. * @param array $options
  246. *
  247. * @return RequestInterface
  248. */
  249. private function applyOptions(RequestInterface $request, array &$options)
  250. {
  251. $modify = [];
  252. if (isset($options['form_params'])) {
  253. if (isset($options['multipart'])) {
  254. throw new \InvalidArgumentException('You cannot use '
  255. . 'form_params and multipart at the same time. Use the '
  256. . 'form_params option if you want to send application/'
  257. . 'x-www-form-urlencoded requests, and the multipart '
  258. . 'option to send multipart/form-data requests.');
  259. }
  260. $options['body'] = http_build_query($options['form_params'], null, '&');
  261. unset($options['form_params']);
  262. $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
  263. }
  264. if (isset($options['multipart'])) {
  265. $elements = $options['multipart'];
  266. unset($options['multipart']);
  267. $options['body'] = new Psr7\MultipartStream($elements);
  268. }
  269. if (!empty($options['decode_content'])
  270. && $options['decode_content'] !== true
  271. ) {
  272. $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
  273. }
  274. if (isset($options['headers'])) {
  275. if (isset($modify['set_headers'])) {
  276. $modify['set_headers'] = $options['headers'] + $modify['set_headers'];
  277. } else {
  278. $modify['set_headers'] = $options['headers'];
  279. }
  280. unset($options['headers']);
  281. }
  282. if (isset($options['body'])) {
  283. if (is_array($options['body'])) {
  284. $this->invalidBody();
  285. }
  286. $modify['body'] = Psr7\stream_for($options['body']);
  287. unset($options['body']);
  288. }
  289. if (!empty($options['auth'])) {
  290. $value = $options['auth'];
  291. $type = is_array($value)
  292. ? (isset($value[2]) ? strtolower($value[2]) : 'basic')
  293. : $value;
  294. $config['auth'] = $value;
  295. switch (strtolower($type)) {
  296. case 'basic':
  297. $modify['set_headers']['Authorization'] = 'Basic '
  298. . base64_encode("$value[0]:$value[1]");
  299. break;
  300. case 'digest':
  301. // @todo: Do not rely on curl
  302. $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
  303. $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
  304. break;
  305. }
  306. }
  307. if (isset($options['query'])) {
  308. $value = $options['query'];
  309. if (is_array($value)) {
  310. $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
  311. }
  312. if (!is_string($value)) {
  313. throw new \InvalidArgumentException('query must be a string or array');
  314. }
  315. $modify['query'] = $value;
  316. unset($options['query']);
  317. }
  318. if (isset($options['json'])) {
  319. $modify['body'] = Psr7\stream_for(json_encode($options['json']));
  320. $options['_conditional']['Content-Type'] = 'application/json';
  321. unset($options['json']);
  322. }
  323. $request = Psr7\modify_request($request, $modify);
  324. if ($request->getBody() instanceof Psr7\MultipartStream) {
  325. // Use a multipart/form-data POST if a Content-Type is not set.
  326. $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
  327. . $request->getBody()->getBoundary();
  328. }
  329. // Merge in conditional headers if they are not present.
  330. if (isset($options['_conditional'])) {
  331. // Build up the changes so it's in a single clone of the message.
  332. $modify = [];
  333. foreach ($options['_conditional'] as $k => $v) {
  334. if (!$request->hasHeader($k)) {
  335. $modify['set_headers'][$k] = $v;
  336. }
  337. }
  338. $request = Psr7\modify_request($request, $modify);
  339. // Don't pass this internal value along to middleware/handlers.
  340. unset($options['_conditional']);
  341. }
  342. return $request;
  343. }
  344. private function invalidBody()
  345. {
  346. throw new \InvalidArgumentException('Passing in the "body" request '
  347. . 'option as an array to send a POST request has been deprecated. '
  348. . 'Please use the "form_params" request option to send a '
  349. . 'application/x-www-form-urlencoded request, or a the "multipart" '
  350. . 'request option to send a multipart/form-data request.');
  351. }
  352. }