Client.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. }
  64. // Convert the base_uri to a UriInterface
  65. if (isset($config['base_uri'])) {
  66. $config['base_uri'] = Psr7\uri_for($config['base_uri']);
  67. }
  68. $this->configureDefaults($config);
  69. }
  70. public function __call($method, $args)
  71. {
  72. if (count($args) < 1) {
  73. throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
  74. }
  75. $uri = $args[0];
  76. $opts = isset($args[1]) ? $args[1] : [];
  77. return substr($method, -5) === 'Async'
  78. ? $this->requestAsync(substr($method, 0, -5), $uri, $opts)
  79. : $this->request($method, $uri, $opts);
  80. }
  81. public function sendAsync(RequestInterface $request, array $options = [])
  82. {
  83. // Merge the base URI into the request URI if needed.
  84. $options = $this->prepareDefaults($options);
  85. return $this->transfer(
  86. $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
  87. $options
  88. );
  89. }
  90. public function send(RequestInterface $request, array $options = [])
  91. {
  92. $options[RequestOptions::SYNCHRONOUS] = true;
  93. return $this->sendAsync($request, $options)->wait();
  94. }
  95. public function requestAsync($method, $uri = '', array $options = [])
  96. {
  97. $options = $this->prepareDefaults($options);
  98. // Remove request modifying parameter because it can be done up-front.
  99. $headers = isset($options['headers']) ? $options['headers'] : [];
  100. $body = isset($options['body']) ? $options['body'] : null;
  101. $version = isset($options['version']) ? $options['version'] : '1.1';
  102. // Merge the URI into the base URI.
  103. $uri = $this->buildUri($uri, $options);
  104. if (is_array($body)) {
  105. $this->invalidBody();
  106. }
  107. $request = new Psr7\Request($method, $uri, $headers, $body, $version);
  108. // Remove the option so that they are not doubly-applied.
  109. unset($options['headers'], $options['body'], $options['version']);
  110. return $this->transfer($request, $options);
  111. }
  112. public function request($method, $uri = '', array $options = [])
  113. {
  114. $options[RequestOptions::SYNCHRONOUS] = true;
  115. return $this->requestAsync($method, $uri, $options)->wait();
  116. }
  117. public function getConfig($option = null)
  118. {
  119. return $option === null
  120. ? $this->config
  121. : (isset($this->config[$option]) ? $this->config[$option] : null);
  122. }
  123. private function buildUri($uri, array $config)
  124. {
  125. // for BC we accept null which would otherwise fail in uri_for
  126. $uri = Psr7\uri_for($uri === null ? '' : $uri);
  127. if (isset($config['base_uri'])) {
  128. $uri = Psr7\UriResolver::resolve(Psr7\uri_for($config['base_uri']), $uri);
  129. }
  130. return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $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. // We can only trust the HTTP_PROXY environment variable in a CLI
  148. // process due to the fact that PHP has no reliable mechanism to
  149. // get environment variables that start with "HTTP_".
  150. if (php_sapi_name() == 'cli' && getenv('HTTP_PROXY')) {
  151. $defaults['proxy']['http'] = getenv('HTTP_PROXY');
  152. }
  153. if ($proxy = getenv('HTTPS_PROXY')) {
  154. $defaults['proxy']['https'] = $proxy;
  155. }
  156. if ($noProxy = getenv('NO_PROXY')) {
  157. $cleanedNoProxy = str_replace(' ', '', $noProxy);
  158. $defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
  159. }
  160. $this->config = $config + $defaults;
  161. if (!empty($config['cookies']) && $config['cookies'] === true) {
  162. $this->config['cookies'] = new CookieJar();
  163. }
  164. // Add the default user-agent header.
  165. if (!isset($this->config['headers'])) {
  166. $this->config['headers'] = ['User-Agent' => default_user_agent()];
  167. } else {
  168. // Add the User-Agent header if one was not already set.
  169. foreach (array_keys($this->config['headers']) as $name) {
  170. if (strtolower($name) === 'user-agent') {
  171. return;
  172. }
  173. }
  174. $this->config['headers']['User-Agent'] = default_user_agent();
  175. }
  176. }
  177. /**
  178. * Merges default options into the array.
  179. *
  180. * @param array $options Options to modify by reference
  181. *
  182. * @return array
  183. */
  184. private function prepareDefaults($options)
  185. {
  186. $defaults = $this->config;
  187. if (!empty($defaults['headers'])) {
  188. // Default headers are only added if they are not present.
  189. $defaults['_conditional'] = $defaults['headers'];
  190. unset($defaults['headers']);
  191. }
  192. // Special handling for headers is required as they are added as
  193. // conditional headers and as headers passed to a request ctor.
  194. if (array_key_exists('headers', $options)) {
  195. // Allows default headers to be unset.
  196. if ($options['headers'] === null) {
  197. $defaults['_conditional'] = null;
  198. unset($options['headers']);
  199. } elseif (!is_array($options['headers'])) {
  200. throw new \InvalidArgumentException('headers must be an array');
  201. }
  202. }
  203. // Shallow merge defaults underneath options.
  204. $result = $options + $defaults;
  205. // Remove null values.
  206. foreach ($result as $k => $v) {
  207. if ($v === null) {
  208. unset($result[$k]);
  209. }
  210. }
  211. return $result;
  212. }
  213. /**
  214. * Transfers the given request and applies request options.
  215. *
  216. * The URI of the request is not modified and the request options are used
  217. * as-is without merging in default options.
  218. *
  219. * @param RequestInterface $request
  220. * @param array $options
  221. *
  222. * @return Promise\PromiseInterface
  223. */
  224. private function transfer(RequestInterface $request, array $options)
  225. {
  226. // save_to -> sink
  227. if (isset($options['save_to'])) {
  228. $options['sink'] = $options['save_to'];
  229. unset($options['save_to']);
  230. }
  231. // exceptions -> http_errors
  232. if (isset($options['exceptions'])) {
  233. $options['http_errors'] = $options['exceptions'];
  234. unset($options['exceptions']);
  235. }
  236. $request = $this->applyOptions($request, $options);
  237. $handler = $options['handler'];
  238. try {
  239. return Promise\promise_for($handler($request, $options));
  240. } catch (\Exception $e) {
  241. return Promise\rejection_for($e);
  242. }
  243. }
  244. /**
  245. * Applies the array of request options to a request.
  246. *
  247. * @param RequestInterface $request
  248. * @param array $options
  249. *
  250. * @return RequestInterface
  251. */
  252. private function applyOptions(RequestInterface $request, array &$options)
  253. {
  254. $modify = [];
  255. if (isset($options['form_params'])) {
  256. if (isset($options['multipart'])) {
  257. throw new \InvalidArgumentException('You cannot use '
  258. . 'form_params and multipart at the same time. Use the '
  259. . 'form_params option if you want to send application/'
  260. . 'x-www-form-urlencoded requests, and the multipart '
  261. . 'option to send multipart/form-data requests.');
  262. }
  263. $options['body'] = http_build_query($options['form_params'], '', '&');
  264. unset($options['form_params']);
  265. $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
  266. }
  267. if (isset($options['multipart'])) {
  268. $options['body'] = new Psr7\MultipartStream($options['multipart']);
  269. unset($options['multipart']);
  270. }
  271. if (isset($options['json'])) {
  272. $options['body'] = \GuzzleHttp\json_encode($options['json']);
  273. unset($options['json']);
  274. $options['_conditional']['Content-Type'] = 'application/json';
  275. }
  276. if (!empty($options['decode_content'])
  277. && $options['decode_content'] !== true
  278. ) {
  279. $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
  280. }
  281. if (isset($options['headers'])) {
  282. if (isset($modify['set_headers'])) {
  283. $modify['set_headers'] = $options['headers'] + $modify['set_headers'];
  284. } else {
  285. $modify['set_headers'] = $options['headers'];
  286. }
  287. unset($options['headers']);
  288. }
  289. if (isset($options['body'])) {
  290. if (is_array($options['body'])) {
  291. $this->invalidBody();
  292. }
  293. $modify['body'] = Psr7\stream_for($options['body']);
  294. unset($options['body']);
  295. }
  296. if (!empty($options['auth']) && is_array($options['auth'])) {
  297. $value = $options['auth'];
  298. $type = isset($value[2]) ? strtolower($value[2]) : 'basic';
  299. switch ($type) {
  300. case 'basic':
  301. $modify['set_headers']['Authorization'] = 'Basic '
  302. . base64_encode("$value[0]:$value[1]");
  303. break;
  304. case 'digest':
  305. // @todo: Do not rely on curl
  306. $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
  307. $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
  308. break;
  309. }
  310. }
  311. if (isset($options['query'])) {
  312. $value = $options['query'];
  313. if (is_array($value)) {
  314. $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
  315. }
  316. if (!is_string($value)) {
  317. throw new \InvalidArgumentException('query must be a string or array');
  318. }
  319. $modify['query'] = $value;
  320. unset($options['query']);
  321. }
  322. // Ensure that sink is not an invalid value.
  323. if (isset($options['sink'])) {
  324. // TODO: Add more sink validation?
  325. if (is_bool($options['sink'])) {
  326. throw new \InvalidArgumentException('sink must not be a boolean');
  327. }
  328. }
  329. $request = Psr7\modify_request($request, $modify);
  330. if ($request->getBody() instanceof Psr7\MultipartStream) {
  331. // Use a multipart/form-data POST if a Content-Type is not set.
  332. $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
  333. . $request->getBody()->getBoundary();
  334. }
  335. // Merge in conditional headers if they are not present.
  336. if (isset($options['_conditional'])) {
  337. // Build up the changes so it's in a single clone of the message.
  338. $modify = [];
  339. foreach ($options['_conditional'] as $k => $v) {
  340. if (!$request->hasHeader($k)) {
  341. $modify['set_headers'][$k] = $v;
  342. }
  343. }
  344. $request = Psr7\modify_request($request, $modify);
  345. // Don't pass this internal value along to middleware/handlers.
  346. unset($options['_conditional']);
  347. }
  348. return $request;
  349. }
  350. private function invalidBody()
  351. {
  352. throw new \InvalidArgumentException('Passing in the "body" request '
  353. . 'option as an array to send a POST request has been deprecated. '
  354. . 'Please use the "form_params" request option to send a '
  355. . 'application/x-www-form-urlencoded request, or a the "multipart" '
  356. . 'request option to send a multipart/form-data request.');
  357. }
  358. }