Client.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. /**
  10. * @method ResponseInterface get(string|UriInterface $uri, array $options = [])
  11. * @method ResponseInterface head(string|UriInterface $uri, array $options = [])
  12. * @method ResponseInterface put(string|UriInterface $uri, array $options = [])
  13. * @method ResponseInterface post(string|UriInterface $uri, array $options = [])
  14. * @method ResponseInterface patch(string|UriInterface $uri, array $options = [])
  15. * @method ResponseInterface delete(string|UriInterface $uri, array $options = [])
  16. * @method Promise\PromiseInterface getAsync(string|UriInterface $uri, array $options = [])
  17. * @method Promise\PromiseInterface headAsync(string|UriInterface $uri, array $options = [])
  18. * @method Promise\PromiseInterface putAsync(string|UriInterface $uri, array $options = [])
  19. * @method Promise\PromiseInterface postAsync(string|UriInterface $uri, array $options = [])
  20. * @method Promise\PromiseInterface patchAsync(string|UriInterface $uri, array $options = [])
  21. * @method Promise\PromiseInterface deleteAsync(string|UriInterface $uri, array $options = [])
  22. */
  23. class Client implements ClientInterface
  24. {
  25. /** @var array Default request options */
  26. private $config;
  27. /**
  28. * Clients accept an array of constructor parameters.
  29. *
  30. * Here's an example of creating a client using a base_uri and an array of
  31. * default request options to apply to each request:
  32. *
  33. * $client = new Client([
  34. * 'base_uri' => 'http://www.foo.com/1.0/',
  35. * 'timeout' => 0,
  36. * 'allow_redirects' => false,
  37. * 'proxy' => '192.168.16.1:10'
  38. * ]);
  39. *
  40. * Client configuration settings include the following options:
  41. *
  42. * - handler: (callable) Function that transfers HTTP requests over the
  43. * wire. The function is called with a Psr7\Http\Message\RequestInterface
  44. * and array of transfer options, and must return a
  45. * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
  46. * Psr7\Http\Message\ResponseInterface on success. "handler" is a
  47. * constructor only option that cannot be overridden in per/request
  48. * options. If no handler is provided, a default handler will be created
  49. * that enables all of the request options below by attaching all of the
  50. * default middleware to the handler.
  51. * - base_uri: (string|UriInterface) Base URI of the client that is merged
  52. * into relative URIs. Can be a string or instance of UriInterface.
  53. * - **: any request option
  54. *
  55. * @param array $config Client configuration settings.
  56. *
  57. * @see \GuzzleHttp\RequestOptions for a list of available request options.
  58. */
  59. public function __construct(array $config = [])
  60. {
  61. if (!isset($config['handler'])) {
  62. $config['handler'] = HandlerStack::create();
  63. } elseif (!is_callable($config['handler'])) {
  64. throw new \InvalidArgumentException('handler must be a callable');
  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), $request->hasHeader('Host')),
  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 = '', 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 = '', 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. // for BC we accept null which would otherwise fail in uri_for
  128. $uri = Psr7\uri_for($uri === null ? '' : $uri);
  129. if (isset($config['base_uri'])) {
  130. $uri = Psr7\UriResolver::resolve(Psr7\uri_for($config['base_uri']), $uri);
  131. }
  132. return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
  133. }
  134. /**
  135. * Configures the default options for a client.
  136. *
  137. * @param array $config
  138. */
  139. private function configureDefaults(array $config)
  140. {
  141. $defaults = [
  142. 'allow_redirects' => RedirectMiddleware::$defaultSettings,
  143. 'http_errors' => true,
  144. 'decode_content' => true,
  145. 'verify' => true,
  146. 'cookies' => false
  147. ];
  148. // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
  149. // We can only trust the HTTP_PROXY environment variable in a CLI
  150. // process due to the fact that PHP has no reliable mechanism to
  151. // get environment variables that start with "HTTP_".
  152. if (php_sapi_name() == 'cli' && getenv('HTTP_PROXY')) {
  153. $defaults['proxy']['http'] = getenv('HTTP_PROXY');
  154. }
  155. if ($proxy = getenv('HTTPS_PROXY')) {
  156. $defaults['proxy']['https'] = $proxy;
  157. }
  158. if ($noProxy = getenv('NO_PROXY')) {
  159. $cleanedNoProxy = str_replace(' ', '', $noProxy);
  160. $defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
  161. }
  162. $this->config = $config + $defaults;
  163. if (!empty($config['cookies']) && $config['cookies'] === true) {
  164. $this->config['cookies'] = new CookieJar();
  165. }
  166. // Add the default user-agent header.
  167. if (!isset($this->config['headers'])) {
  168. $this->config['headers'] = ['User-Agent' => default_user_agent()];
  169. } else {
  170. // Add the User-Agent header if one was not already set.
  171. foreach (array_keys($this->config['headers']) as $name) {
  172. if (strtolower($name) === 'user-agent') {
  173. return;
  174. }
  175. }
  176. $this->config['headers']['User-Agent'] = default_user_agent();
  177. }
  178. }
  179. /**
  180. * Merges default options into the array.
  181. *
  182. * @param array $options Options to modify by reference
  183. *
  184. * @return array
  185. */
  186. private function prepareDefaults($options)
  187. {
  188. $defaults = $this->config;
  189. if (!empty($defaults['headers'])) {
  190. // Default headers are only added if they are not present.
  191. $defaults['_conditional'] = $defaults['headers'];
  192. unset($defaults['headers']);
  193. }
  194. // Special handling for headers is required as they are added as
  195. // conditional headers and as headers passed to a request ctor.
  196. if (array_key_exists('headers', $options)) {
  197. // Allows default headers to be unset.
  198. if ($options['headers'] === null) {
  199. $defaults['_conditional'] = null;
  200. unset($options['headers']);
  201. } elseif (!is_array($options['headers'])) {
  202. throw new \InvalidArgumentException('headers must be an array');
  203. }
  204. }
  205. // Shallow merge defaults underneath options.
  206. $result = $options + $defaults;
  207. // Remove null values.
  208. foreach ($result as $k => $v) {
  209. if ($v === null) {
  210. unset($result[$k]);
  211. }
  212. }
  213. return $result;
  214. }
  215. /**
  216. * Transfers the given request and applies request options.
  217. *
  218. * The URI of the request is not modified and the request options are used
  219. * as-is without merging in default options.
  220. *
  221. * @param RequestInterface $request
  222. * @param array $options
  223. *
  224. * @return Promise\PromiseInterface
  225. */
  226. private function transfer(RequestInterface $request, array $options)
  227. {
  228. // save_to -> sink
  229. if (isset($options['save_to'])) {
  230. $options['sink'] = $options['save_to'];
  231. unset($options['save_to']);
  232. }
  233. // exceptions -> http_errors
  234. if (isset($options['exceptions'])) {
  235. $options['http_errors'] = $options['exceptions'];
  236. unset($options['exceptions']);
  237. }
  238. $request = $this->applyOptions($request, $options);
  239. $handler = $options['handler'];
  240. try {
  241. return Promise\promise_for($handler($request, $options));
  242. } catch (\Exception $e) {
  243. return Promise\rejection_for($e);
  244. }
  245. }
  246. /**
  247. * Applies the array of request options to a request.
  248. *
  249. * @param RequestInterface $request
  250. * @param array $options
  251. *
  252. * @return RequestInterface
  253. */
  254. private function applyOptions(RequestInterface $request, array &$options)
  255. {
  256. $modify = [
  257. 'set_headers' => [],
  258. ];
  259. if (isset($options['headers'])) {
  260. $modify['set_headers'] = $options['headers'];
  261. unset($options['headers']);
  262. }
  263. if (isset($options['form_params'])) {
  264. if (isset($options['multipart'])) {
  265. throw new \InvalidArgumentException('You cannot use '
  266. . 'form_params and multipart at the same time. Use the '
  267. . 'form_params option if you want to send application/'
  268. . 'x-www-form-urlencoded requests, and the multipart '
  269. . 'option to send multipart/form-data requests.');
  270. }
  271. $options['body'] = http_build_query($options['form_params'], '', '&');
  272. unset($options['form_params']);
  273. // Ensure that we don't have the header in different case and set the new value.
  274. $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']);
  275. $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
  276. }
  277. if (isset($options['multipart'])) {
  278. $options['body'] = new Psr7\MultipartStream($options['multipart']);
  279. unset($options['multipart']);
  280. }
  281. if (isset($options['json'])) {
  282. $options['body'] = \GuzzleHttp\json_encode($options['json']);
  283. unset($options['json']);
  284. // Ensure that we don't have the header in different case and set the new value.
  285. $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']);
  286. $options['_conditional']['Content-Type'] = 'application/json';
  287. }
  288. if (!empty($options['decode_content'])
  289. && $options['decode_content'] !== true
  290. ) {
  291. // Ensure that we don't have the header in different case and set the new value.
  292. $options['_conditional'] = Psr7\_caseless_remove(['Accept-Encoding'], $options['_conditional']);
  293. $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
  294. }
  295. if (isset($options['body'])) {
  296. if (is_array($options['body'])) {
  297. $this->invalidBody();
  298. }
  299. $modify['body'] = Psr7\stream_for($options['body']);
  300. unset($options['body']);
  301. }
  302. if (!empty($options['auth']) && is_array($options['auth'])) {
  303. $value = $options['auth'];
  304. $type = isset($value[2]) ? strtolower($value[2]) : 'basic';
  305. switch ($type) {
  306. case 'basic':
  307. // Ensure that we don't have the header in different case and set the new value.
  308. $modify['set_headers'] = Psr7\_caseless_remove(['Authorization'], $modify['set_headers']);
  309. $modify['set_headers']['Authorization'] = 'Basic '
  310. . base64_encode("$value[0]:$value[1]");
  311. break;
  312. case 'digest':
  313. // @todo: Do not rely on curl
  314. $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
  315. $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
  316. break;
  317. case 'ntlm':
  318. $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_NTLM;
  319. $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
  320. break;
  321. }
  322. }
  323. if (isset($options['query'])) {
  324. $value = $options['query'];
  325. if (is_array($value)) {
  326. $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
  327. }
  328. if (!is_string($value)) {
  329. throw new \InvalidArgumentException('query must be a string or array');
  330. }
  331. $modify['query'] = $value;
  332. unset($options['query']);
  333. }
  334. // Ensure that sink is not an invalid value.
  335. if (isset($options['sink'])) {
  336. // TODO: Add more sink validation?
  337. if (is_bool($options['sink'])) {
  338. throw new \InvalidArgumentException('sink must not be a boolean');
  339. }
  340. }
  341. $request = Psr7\modify_request($request, $modify);
  342. if ($request->getBody() instanceof Psr7\MultipartStream) {
  343. // Use a multipart/form-data POST if a Content-Type is not set.
  344. // Ensure that we don't have the header in different case and set the new value.
  345. $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']);
  346. $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
  347. . $request->getBody()->getBoundary();
  348. }
  349. // Merge in conditional headers if they are not present.
  350. if (isset($options['_conditional'])) {
  351. // Build up the changes so it's in a single clone of the message.
  352. $modify = [];
  353. foreach ($options['_conditional'] as $k => $v) {
  354. if (!$request->hasHeader($k)) {
  355. $modify['set_headers'][$k] = $v;
  356. }
  357. }
  358. $request = Psr7\modify_request($request, $modify);
  359. // Don't pass this internal value along to middleware/handlers.
  360. unset($options['_conditional']);
  361. }
  362. return $request;
  363. }
  364. private function invalidBody()
  365. {
  366. throw new \InvalidArgumentException('Passing in the "body" request '
  367. . 'option as an array to send a POST request has been deprecated. '
  368. . 'Please use the "form_params" request option to send a '
  369. . 'application/x-www-form-urlencoded request, or the "multipart" '
  370. . 'request option to send a multipart/form-data request.');
  371. }
  372. }