Client.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. namespace GuzzleHttp;
  3. use GuzzleHttp\Cookie\CookieJar;
  4. use GuzzleHttp\Exception\InvalidArgumentException;
  5. use GuzzleHttp\Promise;
  6. use GuzzleHttp\Psr7;
  7. use Psr\Http\Message\RequestInterface;
  8. use Psr\Http\Message\ResponseInterface;
  9. use Psr\Http\Message\UriInterface;
  10. /**
  11. * @method ResponseInterface get(string|UriInterface $uri, array $options = [])
  12. * @method ResponseInterface head(string|UriInterface $uri, array $options = [])
  13. * @method ResponseInterface put(string|UriInterface $uri, array $options = [])
  14. * @method ResponseInterface post(string|UriInterface $uri, array $options = [])
  15. * @method ResponseInterface patch(string|UriInterface $uri, array $options = [])
  16. * @method ResponseInterface delete(string|UriInterface $uri, array $options = [])
  17. * @method Promise\PromiseInterface getAsync(string|UriInterface $uri, array $options = [])
  18. * @method Promise\PromiseInterface headAsync(string|UriInterface $uri, array $options = [])
  19. * @method Promise\PromiseInterface putAsync(string|UriInterface $uri, array $options = [])
  20. * @method Promise\PromiseInterface postAsync(string|UriInterface $uri, array $options = [])
  21. * @method Promise\PromiseInterface patchAsync(string|UriInterface $uri, array $options = [])
  22. * @method Promise\PromiseInterface deleteAsync(string|UriInterface $uri, array $options = [])
  23. */
  24. class Client implements ClientInterface
  25. {
  26. /** @var array Default request options */
  27. private $config;
  28. /**
  29. * Clients accept an array of constructor parameters.
  30. *
  31. * Here's an example of creating a client using a base_uri and an array of
  32. * default request options to apply to each request:
  33. *
  34. * $client = new Client([
  35. * 'base_uri' => 'http://www.foo.com/1.0/',
  36. * 'timeout' => 0,
  37. * 'allow_redirects' => false,
  38. * 'proxy' => '192.168.16.1:10'
  39. * ]);
  40. *
  41. * Client configuration settings include the following options:
  42. *
  43. * - handler: (callable) Function that transfers HTTP requests over the
  44. * wire. The function is called with a Psr7\Http\Message\RequestInterface
  45. * and array of transfer options, and must return a
  46. * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
  47. * Psr7\Http\Message\ResponseInterface on success. "handler" is a
  48. * constructor only option that cannot be overridden in per/request
  49. * options. If no handler is provided, a default handler will be created
  50. * that enables all of the request options below by attaching all of the
  51. * default middleware to the handler.
  52. * - base_uri: (string|UriInterface) Base URI of the client that is merged
  53. * into relative URIs. Can be a string or instance of UriInterface.
  54. * - **: any request option
  55. *
  56. * @param array $config Client configuration settings.
  57. *
  58. * @see \GuzzleHttp\RequestOptions for a list of available request options.
  59. */
  60. public function __construct(array $config = [])
  61. {
  62. if (!isset($config['handler'])) {
  63. $config['handler'] = HandlerStack::create();
  64. } elseif (!is_callable($config['handler'])) {
  65. throw new \InvalidArgumentException('handler must be a callable');
  66. }
  67. // Convert the base_uri to a UriInterface
  68. if (isset($config['base_uri'])) {
  69. $config['base_uri'] = Psr7\uri_for($config['base_uri']);
  70. }
  71. $this->configureDefaults($config);
  72. }
  73. /**
  74. * @param string $method
  75. * @param array $args
  76. *
  77. * @return Promise\PromiseInterface
  78. */
  79. public function __call($method, $args)
  80. {
  81. if (count($args) < 1) {
  82. throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
  83. }
  84. $uri = $args[0];
  85. $opts = isset($args[1]) ? $args[1] : [];
  86. return substr($method, -5) === 'Async'
  87. ? $this->requestAsync(substr($method, 0, -5), $uri, $opts)
  88. : $this->request($method, $uri, $opts);
  89. }
  90. /**
  91. * Asynchronously send an HTTP request.
  92. *
  93. * @param array $options Request options to apply to the given
  94. * request and to the transfer. See \GuzzleHttp\RequestOptions.
  95. *
  96. * @return Promise\PromiseInterface
  97. */
  98. public function sendAsync(RequestInterface $request, array $options = [])
  99. {
  100. // Merge the base URI into the request URI if needed.
  101. $options = $this->prepareDefaults($options);
  102. return $this->transfer(
  103. $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
  104. $options
  105. );
  106. }
  107. /**
  108. * Send an HTTP request.
  109. *
  110. * @param array $options Request options to apply to the given
  111. * request and to the transfer. See \GuzzleHttp\RequestOptions.
  112. *
  113. * @return ResponseInterface
  114. * @throws GuzzleException
  115. */
  116. public function send(RequestInterface $request, array $options = [])
  117. {
  118. $options[RequestOptions::SYNCHRONOUS] = true;
  119. return $this->sendAsync($request, $options)->wait();
  120. }
  121. /**
  122. * Create and send an asynchronous HTTP request.
  123. *
  124. * Use an absolute path to override the base path of the client, or a
  125. * relative path to append to the base path of the client. The URL can
  126. * contain the query string as well. Use an array to provide a URL
  127. * template and additional variables to use in the URL template expansion.
  128. *
  129. * @param string $method HTTP method
  130. * @param string|UriInterface $uri URI object or string.
  131. * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions.
  132. *
  133. * @return Promise\PromiseInterface
  134. */
  135. public function requestAsync($method, $uri = '', array $options = [])
  136. {
  137. $options = $this->prepareDefaults($options);
  138. // Remove request modifying parameter because it can be done up-front.
  139. $headers = isset($options['headers']) ? $options['headers'] : [];
  140. $body = isset($options['body']) ? $options['body'] : null;
  141. $version = isset($options['version']) ? $options['version'] : '1.1';
  142. // Merge the URI into the base URI.
  143. $uri = $this->buildUri($uri, $options);
  144. if (is_array($body)) {
  145. $this->invalidBody();
  146. }
  147. $request = new Psr7\Request($method, $uri, $headers, $body, $version);
  148. // Remove the option so that they are not doubly-applied.
  149. unset($options['headers'], $options['body'], $options['version']);
  150. return $this->transfer($request, $options);
  151. }
  152. /**
  153. * Create and send an HTTP request.
  154. *
  155. * Use an absolute path to override the base path of the client, or a
  156. * relative path to append to the base path of the client. The URL can
  157. * contain the query string as well.
  158. *
  159. * @param string $method HTTP method.
  160. * @param string|UriInterface $uri URI object or string.
  161. * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions.
  162. *
  163. * @return ResponseInterface
  164. * @throws GuzzleException
  165. */
  166. public function request($method, $uri = '', array $options = [])
  167. {
  168. $options[RequestOptions::SYNCHRONOUS] = true;
  169. return $this->requestAsync($method, $uri, $options)->wait();
  170. }
  171. /**
  172. * Get a client configuration option.
  173. *
  174. * These options include default request options of the client, a "handler"
  175. * (if utilized by the concrete client), and a "base_uri" if utilized by
  176. * the concrete client.
  177. *
  178. * @param string|null $option The config option to retrieve.
  179. *
  180. * @return mixed
  181. */
  182. public function getConfig($option = null)
  183. {
  184. return $option === null
  185. ? $this->config
  186. : (isset($this->config[$option]) ? $this->config[$option] : null);
  187. }
  188. /**
  189. * @param string|null $uri
  190. *
  191. * @return UriInterface
  192. */
  193. private function buildUri($uri, array $config)
  194. {
  195. // for BC we accept null which would otherwise fail in uri_for
  196. $uri = Psr7\uri_for($uri === null ? '' : $uri);
  197. if (isset($config['base_uri'])) {
  198. $uri = Psr7\UriResolver::resolve(Psr7\uri_for($config['base_uri']), $uri);
  199. }
  200. if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) {
  201. $idnOptions = ($config['idn_conversion'] === true) ? IDNA_DEFAULT : $config['idn_conversion'];
  202. $uri = Utils::idnUriConvert($uri, $idnOptions);
  203. }
  204. return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
  205. }
  206. /**
  207. * Configures the default options for a client.
  208. *
  209. * @param array $config
  210. * @return void
  211. */
  212. private function configureDefaults(array $config)
  213. {
  214. $defaults = [
  215. 'allow_redirects' => RedirectMiddleware::$defaultSettings,
  216. 'http_errors' => true,
  217. 'decode_content' => true,
  218. 'verify' => true,
  219. 'cookies' => false,
  220. 'idn_conversion' => true,
  221. ];
  222. // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
  223. // We can only trust the HTTP_PROXY environment variable in a CLI
  224. // process due to the fact that PHP has no reliable mechanism to
  225. // get environment variables that start with "HTTP_".
  226. if (php_sapi_name() === 'cli' && getenv('HTTP_PROXY')) {
  227. $defaults['proxy']['http'] = getenv('HTTP_PROXY');
  228. }
  229. if ($proxy = getenv('HTTPS_PROXY')) {
  230. $defaults['proxy']['https'] = $proxy;
  231. }
  232. if ($noProxy = getenv('NO_PROXY')) {
  233. $cleanedNoProxy = str_replace(' ', '', $noProxy);
  234. $defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
  235. }
  236. $this->config = $config + $defaults;
  237. if (!empty($config['cookies']) && $config['cookies'] === true) {
  238. $this->config['cookies'] = new CookieJar();
  239. }
  240. // Add the default user-agent header.
  241. if (!isset($this->config['headers'])) {
  242. $this->config['headers'] = ['User-Agent' => default_user_agent()];
  243. } else {
  244. // Add the User-Agent header if one was not already set.
  245. foreach (array_keys($this->config['headers']) as $name) {
  246. if (strtolower($name) === 'user-agent') {
  247. return;
  248. }
  249. }
  250. $this->config['headers']['User-Agent'] = default_user_agent();
  251. }
  252. }
  253. /**
  254. * Merges default options into the array.
  255. *
  256. * @param array $options Options to modify by reference
  257. *
  258. * @return array
  259. */
  260. private function prepareDefaults(array $options)
  261. {
  262. $defaults = $this->config;
  263. if (!empty($defaults['headers'])) {
  264. // Default headers are only added if they are not present.
  265. $defaults['_conditional'] = $defaults['headers'];
  266. unset($defaults['headers']);
  267. }
  268. // Special handling for headers is required as they are added as
  269. // conditional headers and as headers passed to a request ctor.
  270. if (array_key_exists('headers', $options)) {
  271. // Allows default headers to be unset.
  272. if ($options['headers'] === null) {
  273. $defaults['_conditional'] = [];
  274. unset($options['headers']);
  275. } elseif (!is_array($options['headers'])) {
  276. throw new \InvalidArgumentException('headers must be an array');
  277. }
  278. }
  279. // Shallow merge defaults underneath options.
  280. $result = $options + $defaults;
  281. // Remove null values.
  282. foreach ($result as $k => $v) {
  283. if ($v === null) {
  284. unset($result[$k]);
  285. }
  286. }
  287. return $result;
  288. }
  289. /**
  290. * Transfers the given request and applies request options.
  291. *
  292. * The URI of the request is not modified and the request options are used
  293. * as-is without merging in default options.
  294. *
  295. * @param array $options See \GuzzleHttp\RequestOptions.
  296. *
  297. * @return Promise\PromiseInterface
  298. */
  299. private function transfer(RequestInterface $request, array $options)
  300. {
  301. // save_to -> sink
  302. if (isset($options['save_to'])) {
  303. $options['sink'] = $options['save_to'];
  304. unset($options['save_to']);
  305. }
  306. // exceptions -> http_errors
  307. if (isset($options['exceptions'])) {
  308. $options['http_errors'] = $options['exceptions'];
  309. unset($options['exceptions']);
  310. }
  311. $request = $this->applyOptions($request, $options);
  312. /** @var HandlerStack $handler */
  313. $handler = $options['handler'];
  314. try {
  315. return Promise\promise_for($handler($request, $options));
  316. } catch (\Exception $e) {
  317. return Promise\rejection_for($e);
  318. }
  319. }
  320. /**
  321. * Applies the array of request options to a request.
  322. *
  323. * @param RequestInterface $request
  324. * @param array $options
  325. *
  326. * @return RequestInterface
  327. */
  328. private function applyOptions(RequestInterface $request, array &$options)
  329. {
  330. $modify = [
  331. 'set_headers' => [],
  332. ];
  333. if (isset($options['headers'])) {
  334. $modify['set_headers'] = $options['headers'];
  335. unset($options['headers']);
  336. }
  337. if (isset($options['form_params'])) {
  338. if (isset($options['multipart'])) {
  339. throw new \InvalidArgumentException('You cannot use '
  340. . 'form_params and multipart at the same time. Use the '
  341. . 'form_params option if you want to send application/'
  342. . 'x-www-form-urlencoded requests, and the multipart '
  343. . 'option to send multipart/form-data requests.');
  344. }
  345. $options['body'] = http_build_query($options['form_params'], '', '&');
  346. unset($options['form_params']);
  347. // Ensure that we don't have the header in different case and set the new value.
  348. $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']);
  349. $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
  350. }
  351. if (isset($options['multipart'])) {
  352. $options['body'] = new Psr7\MultipartStream($options['multipart']);
  353. unset($options['multipart']);
  354. }
  355. if (isset($options['json'])) {
  356. $options['body'] = \GuzzleHttp\json_encode($options['json']);
  357. unset($options['json']);
  358. // Ensure that we don't have the header in different case and set the new value.
  359. $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']);
  360. $options['_conditional']['Content-Type'] = 'application/json';
  361. }
  362. if (!empty($options['decode_content'])
  363. && $options['decode_content'] !== true
  364. ) {
  365. // Ensure that we don't have the header in different case and set the new value.
  366. $options['_conditional'] = Psr7\_caseless_remove(['Accept-Encoding'], $options['_conditional']);
  367. $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
  368. }
  369. if (isset($options['body'])) {
  370. if (is_array($options['body'])) {
  371. $this->invalidBody();
  372. }
  373. $modify['body'] = Psr7\stream_for($options['body']);
  374. unset($options['body']);
  375. }
  376. if (!empty($options['auth']) && is_array($options['auth'])) {
  377. $value = $options['auth'];
  378. $type = isset($value[2]) ? strtolower($value[2]) : 'basic';
  379. switch ($type) {
  380. case 'basic':
  381. // Ensure that we don't have the header in different case and set the new value.
  382. $modify['set_headers'] = Psr7\_caseless_remove(['Authorization'], $modify['set_headers']);
  383. $modify['set_headers']['Authorization'] = 'Basic '
  384. . base64_encode("$value[0]:$value[1]");
  385. break;
  386. case 'digest':
  387. // @todo: Do not rely on curl
  388. $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
  389. $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
  390. break;
  391. case 'ntlm':
  392. $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_NTLM;
  393. $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
  394. break;
  395. }
  396. }
  397. if (isset($options['query'])) {
  398. $value = $options['query'];
  399. if (is_array($value)) {
  400. $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
  401. }
  402. if (!is_string($value)) {
  403. throw new \InvalidArgumentException('query must be a string or array');
  404. }
  405. $modify['query'] = $value;
  406. unset($options['query']);
  407. }
  408. // Ensure that sink is not an invalid value.
  409. if (isset($options['sink'])) {
  410. // TODO: Add more sink validation?
  411. if (is_bool($options['sink'])) {
  412. throw new \InvalidArgumentException('sink must not be a boolean');
  413. }
  414. }
  415. $request = Psr7\modify_request($request, $modify);
  416. if ($request->getBody() instanceof Psr7\MultipartStream) {
  417. // Use a multipart/form-data POST if a Content-Type is not set.
  418. // Ensure that we don't have the header in different case and set the new value.
  419. $options['_conditional'] = Psr7\_caseless_remove(['Content-Type'], $options['_conditional']);
  420. $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
  421. . $request->getBody()->getBoundary();
  422. }
  423. // Merge in conditional headers if they are not present.
  424. if (isset($options['_conditional'])) {
  425. // Build up the changes so it's in a single clone of the message.
  426. $modify = [];
  427. foreach ($options['_conditional'] as $k => $v) {
  428. if (!$request->hasHeader($k)) {
  429. $modify['set_headers'][$k] = $v;
  430. }
  431. }
  432. $request = Psr7\modify_request($request, $modify);
  433. // Don't pass this internal value along to middleware/handlers.
  434. unset($options['_conditional']);
  435. }
  436. return $request;
  437. }
  438. /**
  439. * Throw Exception with pre-set message.
  440. * @return void
  441. * @throws InvalidArgumentException Invalid body.
  442. */
  443. private function invalidBody()
  444. {
  445. throw new \InvalidArgumentException('Passing in the "body" request '
  446. . 'option as an array to send a POST request has been deprecated. '
  447. . 'Please use the "form_params" request option to send a '
  448. . 'application/x-www-form-urlencoded request, or the "multipart" '
  449. . 'request option to send a multipart/form-data request.');
  450. }
  451. }