HttpClientTrait.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpClient;
  11. use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
  12. use Symfony\Component\HttpClient\Exception\TransportException;
  13. /**
  14. * Provides the common logic from writing HttpClientInterface implementations.
  15. *
  16. * All methods are static to prevent implementers from creating memory leaks via circular references.
  17. *
  18. * @author Nicolas Grekas <p@tchwork.com>
  19. */
  20. trait HttpClientTrait
  21. {
  22. private static $CHUNK_SIZE = 16372;
  23. /**
  24. * Validates and normalizes method, URL and options, and merges them with defaults.
  25. *
  26. * @throws InvalidArgumentException When a not-supported option is found
  27. */
  28. private static function prepareRequest(?string $method, ?string $url, array $options, array $defaultOptions = [], bool $allowExtraOptions = false): array
  29. {
  30. if (null !== $method) {
  31. if (\strlen($method) !== strspn($method, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')) {
  32. throw new InvalidArgumentException(sprintf('Invalid HTTP method "%s", only uppercase letters are accepted.', $method));
  33. }
  34. if (!$method) {
  35. throw new InvalidArgumentException('The HTTP method can not be empty.');
  36. }
  37. }
  38. $options = self::mergeDefaultOptions($options, $defaultOptions, $allowExtraOptions);
  39. $buffer = $options['buffer'] ?? true;
  40. if ($buffer instanceof \Closure) {
  41. $options['buffer'] = static function (array $headers) use ($buffer) {
  42. if (!\is_bool($buffer = $buffer($headers))) {
  43. if (!\is_array($bufferInfo = @stream_get_meta_data($buffer))) {
  44. throw new \LogicException(sprintf('The closure passed as option "buffer" must return bool or stream resource, got "%s".', get_debug_type($buffer)));
  45. }
  46. if (false === strpbrk($bufferInfo['mode'], 'acew+')) {
  47. throw new \LogicException(sprintf('The stream returned by the closure passed as option "buffer" must be writeable, got mode "%s".', $bufferInfo['mode']));
  48. }
  49. }
  50. return $buffer;
  51. };
  52. } elseif (!\is_bool($buffer)) {
  53. if (!\is_array($bufferInfo = @stream_get_meta_data($buffer))) {
  54. throw new InvalidArgumentException(sprintf('Option "buffer" must be bool, stream resource or Closure, "%s" given.', get_debug_type($buffer)));
  55. }
  56. if (false === strpbrk($bufferInfo['mode'], 'acew+')) {
  57. throw new InvalidArgumentException(sprintf('The stream in option "buffer" must be writeable, mode "%s" given.', $bufferInfo['mode']));
  58. }
  59. }
  60. if (isset($options['json'])) {
  61. if (isset($options['body']) && '' !== $options['body']) {
  62. throw new InvalidArgumentException('Define either the "json" or the "body" option, setting both is not supported.');
  63. }
  64. $options['body'] = self::jsonEncode($options['json']);
  65. unset($options['json']);
  66. if (!isset($options['normalized_headers']['content-type'])) {
  67. $options['normalized_headers']['content-type'] = [$options['headers'][] = 'Content-Type: application/json'];
  68. }
  69. }
  70. if (!isset($options['normalized_headers']['accept'])) {
  71. $options['normalized_headers']['accept'] = [$options['headers'][] = 'Accept: */*'];
  72. }
  73. if (isset($options['body'])) {
  74. $options['body'] = self::normalizeBody($options['body']);
  75. }
  76. if (isset($options['peer_fingerprint'])) {
  77. $options['peer_fingerprint'] = self::normalizePeerFingerprint($options['peer_fingerprint']);
  78. }
  79. // Validate on_progress
  80. if (!\is_callable($onProgress = $options['on_progress'] ?? 'var_dump')) {
  81. throw new InvalidArgumentException(sprintf('Option "on_progress" must be callable, "%s" given.', get_debug_type($onProgress)));
  82. }
  83. if (\is_array($options['auth_basic'] ?? null)) {
  84. $count = \count($options['auth_basic']);
  85. if ($count <= 0 || $count > 2) {
  86. throw new InvalidArgumentException(sprintf('Option "auth_basic" must contain 1 or 2 elements, "%s" given.', $count));
  87. }
  88. $options['auth_basic'] = implode(':', $options['auth_basic']);
  89. }
  90. if (!\is_string($options['auth_basic'] ?? '')) {
  91. throw new InvalidArgumentException(sprintf('Option "auth_basic" must be string or an array, "%s" given.', get_debug_type($options['auth_basic'])));
  92. }
  93. if (isset($options['auth_bearer'])) {
  94. if (!\is_string($options['auth_bearer'])) {
  95. throw new InvalidArgumentException(sprintf('Option "auth_bearer" must be a string, "%s" given.', get_debug_type($options['auth_bearer'])));
  96. }
  97. if (preg_match('{[^\x21-\x7E]}', $options['auth_bearer'])) {
  98. throw new InvalidArgumentException('Invalid character found in option "auth_bearer": '.json_encode($options['auth_bearer']).'.');
  99. }
  100. }
  101. if (isset($options['auth_basic'], $options['auth_bearer'])) {
  102. throw new InvalidArgumentException('Define either the "auth_basic" or the "auth_bearer" option, setting both is not supported.');
  103. }
  104. if (null !== $url) {
  105. // Merge auth with headers
  106. if (($options['auth_basic'] ?? false) && !($options['normalized_headers']['authorization'] ?? false)) {
  107. $options['normalized_headers']['authorization'] = [$options['headers'][] = 'Authorization: Basic '.base64_encode($options['auth_basic'])];
  108. }
  109. // Merge bearer with headers
  110. if (($options['auth_bearer'] ?? false) && !($options['normalized_headers']['authorization'] ?? false)) {
  111. $options['normalized_headers']['authorization'] = [$options['headers'][] = 'Authorization: Bearer '.$options['auth_bearer']];
  112. }
  113. unset($options['auth_basic'], $options['auth_bearer']);
  114. // Parse base URI
  115. if (\is_string($options['base_uri'])) {
  116. $options['base_uri'] = self::parseUrl($options['base_uri']);
  117. }
  118. // Validate and resolve URL
  119. $url = self::parseUrl($url, $options['query']);
  120. $url = self::resolveUrl($url, $options['base_uri'], $defaultOptions['query'] ?? []);
  121. }
  122. // Finalize normalization of options
  123. $options['http_version'] = (string) ($options['http_version'] ?? '') ?: null;
  124. $options['timeout'] = (float) ($options['timeout'] ?? ini_get('default_socket_timeout'));
  125. $options['max_duration'] = isset($options['max_duration']) ? (float) $options['max_duration'] : 0;
  126. return [$url, $options];
  127. }
  128. /**
  129. * @throws InvalidArgumentException When an invalid option is found
  130. */
  131. private static function mergeDefaultOptions(array $options, array $defaultOptions, bool $allowExtraOptions = false): array
  132. {
  133. $options['normalized_headers'] = self::normalizeHeaders($options['headers'] ?? []);
  134. if ($defaultOptions['headers'] ?? false) {
  135. $options['normalized_headers'] += self::normalizeHeaders($defaultOptions['headers']);
  136. }
  137. $options['headers'] = array_merge(...array_values($options['normalized_headers']) ?: [[]]);
  138. if ($resolve = $options['resolve'] ?? false) {
  139. $options['resolve'] = [];
  140. foreach ($resolve as $k => $v) {
  141. $options['resolve'][substr(self::parseUrl('http://'.$k)['authority'], 2)] = (string) $v;
  142. }
  143. }
  144. // Option "query" is never inherited from defaults
  145. $options['query'] = $options['query'] ?? [];
  146. foreach ($defaultOptions as $k => $v) {
  147. if ('normalized_headers' !== $k && !isset($options[$k])) {
  148. $options[$k] = $v;
  149. }
  150. }
  151. if (isset($defaultOptions['extra'])) {
  152. $options['extra'] += $defaultOptions['extra'];
  153. }
  154. if ($resolve = $defaultOptions['resolve'] ?? false) {
  155. foreach ($resolve as $k => $v) {
  156. $options['resolve'] += [substr(self::parseUrl('http://'.$k)['authority'], 2) => (string) $v];
  157. }
  158. }
  159. if ($allowExtraOptions || !$defaultOptions) {
  160. return $options;
  161. }
  162. // Look for unsupported options
  163. foreach ($options as $name => $v) {
  164. if (\array_key_exists($name, $defaultOptions) || 'normalized_headers' === $name) {
  165. continue;
  166. }
  167. if ('auth_ntlm' === $name) {
  168. if (!\extension_loaded('curl')) {
  169. $msg = 'try installing the "curl" extension to use "%s" instead.';
  170. } else {
  171. $msg = 'try using "%s" instead.';
  172. }
  173. throw new InvalidArgumentException(sprintf('Option "auth_ntlm" is not supported by "%s", '.$msg, __CLASS__, CurlHttpClient::class));
  174. }
  175. $alternatives = [];
  176. foreach ($defaultOptions as $key => $v) {
  177. if (levenshtein($name, $key) <= \strlen($name) / 3 || false !== strpos($key, $name)) {
  178. $alternatives[] = $key;
  179. }
  180. }
  181. throw new InvalidArgumentException(sprintf('Unsupported option "%s" passed to "%s", did you mean "%s"?', $name, __CLASS__, implode('", "', $alternatives ?: array_keys($defaultOptions))));
  182. }
  183. return $options;
  184. }
  185. /**
  186. * @return string[][]
  187. *
  188. * @throws InvalidArgumentException When an invalid header is found
  189. */
  190. private static function normalizeHeaders(array $headers): array
  191. {
  192. $normalizedHeaders = [];
  193. foreach ($headers as $name => $values) {
  194. if (\is_object($values) && method_exists($values, '__toString')) {
  195. $values = (string) $values;
  196. }
  197. if (\is_int($name)) {
  198. if (!\is_string($values)) {
  199. throw new InvalidArgumentException(sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
  200. }
  201. [$name, $values] = explode(':', $values, 2);
  202. $values = [ltrim($values)];
  203. } elseif (!is_iterable($values)) {
  204. if (\is_object($values)) {
  205. throw new InvalidArgumentException(sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
  206. }
  207. $values = (array) $values;
  208. }
  209. $lcName = strtolower($name);
  210. $normalizedHeaders[$lcName] = [];
  211. foreach ($values as $value) {
  212. $normalizedHeaders[$lcName][] = $value = $name.': '.$value;
  213. if (\strlen($value) !== strcspn($value, "\r\n\0")) {
  214. throw new InvalidArgumentException(sprintf('Invalid header: CR/LF/NUL found in "%s".', $value));
  215. }
  216. }
  217. }
  218. return $normalizedHeaders;
  219. }
  220. /**
  221. * @param array|string|resource|\Traversable|\Closure $body
  222. *
  223. * @return string|resource|\Closure
  224. *
  225. * @throws InvalidArgumentException When an invalid body is passed
  226. */
  227. private static function normalizeBody($body)
  228. {
  229. if (\is_array($body)) {
  230. return http_build_query($body, '', '&', \PHP_QUERY_RFC1738);
  231. }
  232. if (\is_string($body)) {
  233. return $body;
  234. }
  235. $generatorToCallable = static function (\Generator $body): \Closure {
  236. return static function () use ($body) {
  237. while ($body->valid()) {
  238. $chunk = $body->current();
  239. $body->next();
  240. if ('' !== $chunk) {
  241. return $chunk;
  242. }
  243. }
  244. return '';
  245. };
  246. };
  247. if ($body instanceof \Generator) {
  248. return $generatorToCallable($body);
  249. }
  250. if ($body instanceof \Traversable) {
  251. return $generatorToCallable((static function ($body) { yield from $body; })($body));
  252. }
  253. if ($body instanceof \Closure) {
  254. $r = new \ReflectionFunction($body);
  255. $body = $r->getClosure();
  256. if ($r->isGenerator()) {
  257. $body = $body(self::$CHUNK_SIZE);
  258. return $generatorToCallable($body);
  259. }
  260. return $body;
  261. }
  262. if (!\is_array(@stream_get_meta_data($body))) {
  263. throw new InvalidArgumentException(sprintf('Option "body" must be string, stream resource, iterable or callable, "%s" given.', get_debug_type($body)));
  264. }
  265. return $body;
  266. }
  267. /**
  268. * @param string|string[] $fingerprint
  269. *
  270. * @throws InvalidArgumentException When an invalid fingerprint is passed
  271. */
  272. private static function normalizePeerFingerprint($fingerprint): array
  273. {
  274. if (\is_string($fingerprint)) {
  275. switch (\strlen($fingerprint = str_replace(':', '', $fingerprint))) {
  276. case 32: $fingerprint = ['md5' => $fingerprint]; break;
  277. case 40: $fingerprint = ['sha1' => $fingerprint]; break;
  278. case 44: $fingerprint = ['pin-sha256' => [$fingerprint]]; break;
  279. case 64: $fingerprint = ['sha256' => $fingerprint]; break;
  280. default: throw new InvalidArgumentException(sprintf('Cannot auto-detect fingerprint algorithm for "%s".', $fingerprint));
  281. }
  282. } elseif (\is_array($fingerprint)) {
  283. foreach ($fingerprint as $algo => $hash) {
  284. $fingerprint[$algo] = 'pin-sha256' === $algo ? (array) $hash : str_replace(':', '', $hash);
  285. }
  286. } else {
  287. throw new InvalidArgumentException(sprintf('Option "peer_fingerprint" must be string or array, "%s" given.', get_debug_type($fingerprint)));
  288. }
  289. return $fingerprint;
  290. }
  291. /**
  292. * @param mixed $value
  293. *
  294. * @throws InvalidArgumentException When the value cannot be json-encoded
  295. */
  296. private static function jsonEncode($value, int $flags = null, int $maxDepth = 512): string
  297. {
  298. $flags = $flags ?? (\JSON_HEX_TAG | \JSON_HEX_APOS | \JSON_HEX_AMP | \JSON_HEX_QUOT | \JSON_PRESERVE_ZERO_FRACTION);
  299. try {
  300. $value = json_encode($value, $flags | (\PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0), $maxDepth);
  301. } catch (\JsonException $e) {
  302. throw new InvalidArgumentException('Invalid value for "json" option: '.$e->getMessage());
  303. }
  304. if (\PHP_VERSION_ID < 70300 && \JSON_ERROR_NONE !== json_last_error() && (false === $value || !($flags & \JSON_PARTIAL_OUTPUT_ON_ERROR))) {
  305. throw new InvalidArgumentException('Invalid value for "json" option: '.json_last_error_msg());
  306. }
  307. return $value;
  308. }
  309. /**
  310. * Resolves a URL against a base URI.
  311. *
  312. * @see https://tools.ietf.org/html/rfc3986#section-5.2.2
  313. *
  314. * @throws InvalidArgumentException When an invalid URL is passed
  315. */
  316. private static function resolveUrl(array $url, ?array $base, array $queryDefaults = []): array
  317. {
  318. if (null !== $base && '' === ($base['scheme'] ?? '').($base['authority'] ?? '')) {
  319. throw new InvalidArgumentException(sprintf('Invalid "base_uri" option: host or scheme is missing in "%s".', implode('', $base)));
  320. }
  321. if (null === $url['scheme'] && (null === $base || null === $base['scheme'])) {
  322. throw new InvalidArgumentException(sprintf('Invalid URL: scheme is missing in "%s". Did you forget to add "http(s)://"?', implode('', $base ?? $url)));
  323. }
  324. if (null === $base && '' === $url['scheme'].$url['authority']) {
  325. throw new InvalidArgumentException(sprintf('Invalid URL: no "base_uri" option was provided and host or scheme is missing in "%s".', implode('', $url)));
  326. }
  327. if (null !== $url['scheme']) {
  328. $url['path'] = self::removeDotSegments($url['path'] ?? '');
  329. } else {
  330. if (null !== $url['authority']) {
  331. $url['path'] = self::removeDotSegments($url['path'] ?? '');
  332. } else {
  333. if (null === $url['path']) {
  334. $url['path'] = $base['path'];
  335. $url['query'] = $url['query'] ?? $base['query'];
  336. } else {
  337. if ('/' !== $url['path'][0]) {
  338. if (null === $base['path']) {
  339. $url['path'] = '/'.$url['path'];
  340. } else {
  341. $segments = explode('/', $base['path']);
  342. array_splice($segments, -1, 1, [$url['path']]);
  343. $url['path'] = implode('/', $segments);
  344. }
  345. }
  346. $url['path'] = self::removeDotSegments($url['path']);
  347. }
  348. $url['authority'] = $base['authority'];
  349. if ($queryDefaults) {
  350. $url['query'] = '?'.self::mergeQueryString(substr($url['query'] ?? '', 1), $queryDefaults, false);
  351. }
  352. }
  353. $url['scheme'] = $base['scheme'];
  354. }
  355. if ('' === ($url['path'] ?? '')) {
  356. $url['path'] = '/';
  357. }
  358. return $url;
  359. }
  360. /**
  361. * Parses a URL and fixes its encoding if needed.
  362. *
  363. * @throws InvalidArgumentException When an invalid URL is passed
  364. */
  365. private static function parseUrl(string $url, array $query = [], array $allowedSchemes = ['http' => 80, 'https' => 443]): array
  366. {
  367. if (false === $parts = parse_url($url)) {
  368. throw new InvalidArgumentException(sprintf('Malformed URL "%s".', $url));
  369. }
  370. if ($query) {
  371. $parts['query'] = self::mergeQueryString($parts['query'] ?? null, $query, true);
  372. }
  373. $port = $parts['port'] ?? 0;
  374. if (null !== $scheme = $parts['scheme'] ?? null) {
  375. if (!isset($allowedSchemes[$scheme = strtolower($scheme)])) {
  376. throw new InvalidArgumentException(sprintf('Unsupported scheme in "%s".', $url));
  377. }
  378. $port = $allowedSchemes[$scheme] === $port ? 0 : $port;
  379. $scheme .= ':';
  380. }
  381. if (null !== $host = $parts['host'] ?? null) {
  382. if (!\defined('INTL_IDNA_VARIANT_UTS46') && preg_match('/[\x80-\xFF]/', $host)) {
  383. throw new InvalidArgumentException(sprintf('Unsupported IDN "%s", try enabling the "intl" PHP extension or running "composer require symfony/polyfill-intl-idn".', $host));
  384. }
  385. $host = \defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($host, \IDNA_DEFAULT, \INTL_IDNA_VARIANT_UTS46) ?: strtolower($host) : strtolower($host);
  386. $host .= $port ? ':'.$port : '';
  387. }
  388. foreach (['user', 'pass', 'path', 'query', 'fragment'] as $part) {
  389. if (!isset($parts[$part])) {
  390. continue;
  391. }
  392. if (false !== strpos($parts[$part], '%')) {
  393. // https://tools.ietf.org/html/rfc3986#section-2.3
  394. $parts[$part] = preg_replace_callback('/%(?:2[DE]|3[0-9]|[46][1-9A-F]|5F|[57][0-9A]|7E)++/i', function ($m) { return rawurldecode($m[0]); }, $parts[$part]);
  395. }
  396. // https://tools.ietf.org/html/rfc3986#section-3.3
  397. $parts[$part] = preg_replace_callback("#[^-A-Za-z0-9._~!$&/'()*+,;=:@%]++#", function ($m) { return rawurlencode($m[0]); }, $parts[$part]);
  398. }
  399. return [
  400. 'scheme' => $scheme,
  401. 'authority' => null !== $host ? '//'.(isset($parts['user']) ? $parts['user'].(isset($parts['pass']) ? ':'.$parts['pass'] : '').'@' : '').$host : null,
  402. 'path' => isset($parts['path'][0]) ? $parts['path'] : null,
  403. 'query' => isset($parts['query']) ? '?'.$parts['query'] : null,
  404. 'fragment' => isset($parts['fragment']) ? '#'.$parts['fragment'] : null,
  405. ];
  406. }
  407. /**
  408. * Removes dot-segments from a path.
  409. *
  410. * @see https://tools.ietf.org/html/rfc3986#section-5.2.4
  411. */
  412. private static function removeDotSegments(string $path)
  413. {
  414. $result = '';
  415. while (!\in_array($path, ['', '.', '..'], true)) {
  416. if ('.' === $path[0] && (0 === strpos($path, $p = '../') || 0 === strpos($path, $p = './'))) {
  417. $path = substr($path, \strlen($p));
  418. } elseif ('/.' === $path || 0 === strpos($path, '/./')) {
  419. $path = substr_replace($path, '/', 0, 3);
  420. } elseif ('/..' === $path || 0 === strpos($path, '/../')) {
  421. $i = strrpos($result, '/');
  422. $result = $i ? substr($result, 0, $i) : '';
  423. $path = substr_replace($path, '/', 0, 4);
  424. } else {
  425. $i = strpos($path, '/', 1) ?: \strlen($path);
  426. $result .= substr($path, 0, $i);
  427. $path = substr($path, $i);
  428. }
  429. }
  430. return $result;
  431. }
  432. /**
  433. * Merges and encodes a query array with a query string.
  434. *
  435. * @throws InvalidArgumentException When an invalid query-string value is passed
  436. */
  437. private static function mergeQueryString(?string $queryString, array $queryArray, bool $replace): ?string
  438. {
  439. if (!$queryArray) {
  440. return $queryString;
  441. }
  442. $query = [];
  443. if (null !== $queryString) {
  444. foreach (explode('&', $queryString) as $v) {
  445. if ('' !== $v) {
  446. $k = urldecode(explode('=', $v, 2)[0]);
  447. $query[$k] = (isset($query[$k]) ? $query[$k].'&' : '').$v;
  448. }
  449. }
  450. }
  451. if ($replace) {
  452. foreach ($queryArray as $k => $v) {
  453. if (null === $v) {
  454. unset($query[$k]);
  455. }
  456. }
  457. }
  458. $queryString = http_build_query($queryArray, '', '&', \PHP_QUERY_RFC3986);
  459. $queryArray = [];
  460. if ($queryString) {
  461. foreach (explode('&', $queryString) as $v) {
  462. $queryArray[rawurldecode(explode('=', $v, 2)[0])] = $v;
  463. }
  464. }
  465. return implode('&', $replace ? array_replace($query, $queryArray) : ($query + $queryArray));
  466. }
  467. /**
  468. * Loads proxy configuration from the same environment variables as curl when no proxy is explicitly set.
  469. */
  470. private static function getProxy(?string $proxy, array $url, ?string $noProxy): ?array
  471. {
  472. if (null === $proxy) {
  473. // Ignore HTTP_PROXY except on the CLI to work around httpoxy set of vulnerabilities
  474. $proxy = $_SERVER['http_proxy'] ?? (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? $_SERVER['HTTP_PROXY'] ?? null : null) ?? $_SERVER['all_proxy'] ?? $_SERVER['ALL_PROXY'] ?? null;
  475. if ('https:' === $url['scheme']) {
  476. $proxy = $_SERVER['https_proxy'] ?? $_SERVER['HTTPS_PROXY'] ?? $proxy;
  477. }
  478. }
  479. if (null === $proxy) {
  480. return null;
  481. }
  482. $proxy = (parse_url($proxy) ?: []) + ['scheme' => 'http'];
  483. if (!isset($proxy['host'])) {
  484. throw new TransportException('Invalid HTTP proxy: host is missing.');
  485. }
  486. if ('http' === $proxy['scheme']) {
  487. $proxyUrl = 'tcp://'.$proxy['host'].':'.($proxy['port'] ?? '80');
  488. } elseif ('https' === $proxy['scheme']) {
  489. $proxyUrl = 'ssl://'.$proxy['host'].':'.($proxy['port'] ?? '443');
  490. } else {
  491. throw new TransportException(sprintf('Unsupported proxy scheme "%s": "http" or "https" expected.', $proxy['scheme']));
  492. }
  493. $noProxy = $noProxy ?? $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '';
  494. $noProxy = $noProxy ? preg_split('/[\s,]+/', $noProxy) : [];
  495. return [
  496. 'url' => $proxyUrl,
  497. 'auth' => isset($proxy['user']) ? 'Basic '.base64_encode(rawurldecode($proxy['user']).':'.rawurldecode($proxy['pass'] ?? '')) : null,
  498. 'no_proxy' => $noProxy,
  499. ];
  500. }
  501. private static function shouldBuffer(array $headers): bool
  502. {
  503. if (null === $contentType = $headers['content-type'][0] ?? null) {
  504. return false;
  505. }
  506. if (false !== $i = strpos($contentType, ';')) {
  507. $contentType = substr($contentType, 0, $i);
  508. }
  509. return $contentType && preg_match('#^(?:text/|application/(?:.+\+)?(?:json|xml)$)#i', $contentType);
  510. }
  511. }