Utils.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <?php
  2. namespace GuzzleHttp;
  3. use GuzzleHttp\Exception\InvalidArgumentException;
  4. use GuzzleHttp\Handler\CurlHandler;
  5. use GuzzleHttp\Handler\CurlMultiHandler;
  6. use GuzzleHttp\Handler\Proxy;
  7. use GuzzleHttp\Handler\StreamHandler;
  8. use Psr\Http\Message\UriInterface;
  9. final class Utils
  10. {
  11. /**
  12. * Debug function used to describe the provided value type and class.
  13. *
  14. * @param mixed $input
  15. *
  16. * @return string Returns a string containing the type of the variable and
  17. * if a class is provided, the class name.
  18. */
  19. public static function describeType($input): string
  20. {
  21. switch (\gettype($input)) {
  22. case 'object':
  23. return 'object(' . \get_class($input) . ')';
  24. case 'array':
  25. return 'array(' . \count($input) . ')';
  26. default:
  27. \ob_start();
  28. \var_dump($input);
  29. // normalize float vs double
  30. /** @var string $varDumpContent */
  31. $varDumpContent = \ob_get_clean();
  32. return \str_replace('double(', 'float(', \rtrim($varDumpContent));
  33. }
  34. }
  35. /**
  36. * Parses an array of header lines into an associative array of headers.
  37. *
  38. * @param iterable $lines Header lines array of strings in the following
  39. * format: "Name: Value"
  40. */
  41. public static function headersFromLines(iterable $lines): array
  42. {
  43. $headers = [];
  44. foreach ($lines as $line) {
  45. $parts = \explode(':', $line, 2);
  46. $headers[\trim($parts[0])][] = isset($parts[1]) ? \trim($parts[1]) : null;
  47. }
  48. return $headers;
  49. }
  50. /**
  51. * Returns a debug stream based on the provided variable.
  52. *
  53. * @param mixed $value Optional value
  54. *
  55. * @return resource
  56. */
  57. public static function debugResource($value = null)
  58. {
  59. if (\is_resource($value)) {
  60. return $value;
  61. }
  62. if (\defined('STDOUT')) {
  63. return \STDOUT;
  64. }
  65. return \GuzzleHttp\Psr7\Utils::tryFopen('php://output', 'w');
  66. }
  67. /**
  68. * Chooses and creates a default handler to use based on the environment.
  69. *
  70. * The returned handler is not wrapped by any default middlewares.
  71. *
  72. * @throws \RuntimeException if no viable Handler is available.
  73. *
  74. * @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the best handler for the given system.
  75. */
  76. public static function chooseHandler(): callable
  77. {
  78. $handler = null;
  79. if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) {
  80. $handler = Proxy::wrapSync(new CurlMultiHandler(), new CurlHandler());
  81. } elseif (\function_exists('curl_exec')) {
  82. $handler = new CurlHandler();
  83. } elseif (\function_exists('curl_multi_exec')) {
  84. $handler = new CurlMultiHandler();
  85. }
  86. if (\ini_get('allow_url_fopen')) {
  87. $handler = $handler
  88. ? Proxy::wrapStreaming($handler, new StreamHandler())
  89. : new StreamHandler();
  90. } elseif (!$handler) {
  91. throw new \RuntimeException('GuzzleHttp requires cURL, the allow_url_fopen ini setting, or a custom HTTP handler.');
  92. }
  93. return $handler;
  94. }
  95. /**
  96. * Get the default User-Agent string to use with Guzzle.
  97. */
  98. public static function defaultUserAgent(): string
  99. {
  100. return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION);
  101. }
  102. /**
  103. * Returns the default cacert bundle for the current system.
  104. *
  105. * First, the openssl.cafile and curl.cainfo php.ini settings are checked.
  106. * If those settings are not configured, then the common locations for
  107. * bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
  108. * and Windows are checked. If any of these file locations are found on
  109. * disk, they will be utilized.
  110. *
  111. * Note: the result of this function is cached for subsequent calls.
  112. *
  113. * @throws \RuntimeException if no bundle can be found.
  114. *
  115. * @deprecated Utils::defaultCaBundle will be removed in guzzlehttp/guzzle:8.0. This method is not needed in PHP 5.6+.
  116. */
  117. public static function defaultCaBundle(): string
  118. {
  119. static $cached = null;
  120. static $cafiles = [
  121. // Red Hat, CentOS, Fedora (provided by the ca-certificates package)
  122. '/etc/pki/tls/certs/ca-bundle.crt',
  123. // Ubuntu, Debian (provided by the ca-certificates package)
  124. '/etc/ssl/certs/ca-certificates.crt',
  125. // FreeBSD (provided by the ca_root_nss package)
  126. '/usr/local/share/certs/ca-root-nss.crt',
  127. // SLES 12 (provided by the ca-certificates package)
  128. '/var/lib/ca-certificates/ca-bundle.pem',
  129. // OS X provided by homebrew (using the default path)
  130. '/usr/local/etc/openssl/cert.pem',
  131. // Google app engine
  132. '/etc/ca-certificates.crt',
  133. // Windows?
  134. 'C:\\windows\\system32\\curl-ca-bundle.crt',
  135. 'C:\\windows\\curl-ca-bundle.crt',
  136. ];
  137. if ($cached) {
  138. return $cached;
  139. }
  140. if ($ca = \ini_get('openssl.cafile')) {
  141. return $cached = $ca;
  142. }
  143. if ($ca = \ini_get('curl.cainfo')) {
  144. return $cached = $ca;
  145. }
  146. foreach ($cafiles as $filename) {
  147. if (\file_exists($filename)) {
  148. return $cached = $filename;
  149. }
  150. }
  151. throw new \RuntimeException(
  152. <<< EOT
  153. No system CA bundle could be found in any of the the common system locations.
  154. PHP versions earlier than 5.6 are not properly configured to use the system's
  155. CA bundle by default. In order to verify peer certificates, you will need to
  156. supply the path on disk to a certificate bundle to the 'verify' request
  157. option: http://docs.guzzlephp.org/en/latest/clients.html#verify. If you do not
  158. need a specific certificate bundle, then Mozilla provides a commonly used CA
  159. bundle which can be downloaded here (provided by the maintainer of cURL):
  160. https://curl.haxx.se/ca/cacert.pem. Once
  161. you have a CA bundle available on disk, you can set the 'openssl.cafile' PHP
  162. ini setting to point to the path to the file, allowing you to omit the 'verify'
  163. request option. See https://curl.haxx.se/docs/sslcerts.html for more
  164. information.
  165. EOT
  166. );
  167. }
  168. /**
  169. * Creates an associative array of lowercase header names to the actual
  170. * header casing.
  171. */
  172. public static function normalizeHeaderKeys(array $headers): array
  173. {
  174. $result = [];
  175. foreach (\array_keys($headers) as $key) {
  176. $result[\strtolower($key)] = $key;
  177. }
  178. return $result;
  179. }
  180. /**
  181. * Returns true if the provided host matches any of the no proxy areas.
  182. *
  183. * This method will strip a port from the host if it is present. Each pattern
  184. * can be matched with an exact match (e.g., "foo.com" == "foo.com") or a
  185. * partial match: (e.g., "foo.com" == "baz.foo.com" and ".foo.com" ==
  186. * "baz.foo.com", but ".foo.com" != "foo.com").
  187. *
  188. * Areas are matched in the following cases:
  189. * 1. "*" (without quotes) always matches any hosts.
  190. * 2. An exact match.
  191. * 3. The area starts with "." and the area is the last part of the host. e.g.
  192. * '.mit.edu' will match any host that ends with '.mit.edu'.
  193. *
  194. * @param string $host Host to check against the patterns.
  195. * @param string[] $noProxyArray An array of host patterns.
  196. *
  197. * @throws InvalidArgumentException
  198. */
  199. public static function isHostInNoProxy(string $host, array $noProxyArray): bool
  200. {
  201. if (\strlen($host) === 0) {
  202. throw new InvalidArgumentException('Empty host provided');
  203. }
  204. // Strip port if present.
  205. [$host] = \explode(':', $host, 2);
  206. foreach ($noProxyArray as $area) {
  207. // Always match on wildcards.
  208. if ($area === '*') {
  209. return true;
  210. }
  211. if (empty($area)) {
  212. // Don't match on empty values.
  213. continue;
  214. }
  215. if ($area === $host) {
  216. // Exact matches.
  217. return true;
  218. }
  219. // Special match if the area when prefixed with ".". Remove any
  220. // existing leading "." and add a new leading ".".
  221. $area = '.' . \ltrim($area, '.');
  222. if (\substr($host, -(\strlen($area))) === $area) {
  223. return true;
  224. }
  225. }
  226. return false;
  227. }
  228. /**
  229. * Wrapper for json_decode that throws when an error occurs.
  230. *
  231. * @param string $json JSON data to parse
  232. * @param bool $assoc When true, returned objects will be converted
  233. * into associative arrays.
  234. * @param int $depth User specified recursion depth.
  235. * @param int $options Bitmask of JSON decode options.
  236. *
  237. * @return object|array|string|int|float|bool|null
  238. *
  239. * @throws InvalidArgumentException if the JSON cannot be decoded.
  240. *
  241. * @link https://www.php.net/manual/en/function.json-decode.php
  242. */
  243. public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
  244. {
  245. $data = \json_decode($json, $assoc, $depth, $options);
  246. if (\JSON_ERROR_NONE !== \json_last_error()) {
  247. throw new InvalidArgumentException('json_decode error: ' . \json_last_error_msg());
  248. }
  249. return $data;
  250. }
  251. /**
  252. * Wrapper for JSON encoding that throws when an error occurs.
  253. *
  254. * @param mixed $value The value being encoded
  255. * @param int $options JSON encode option bitmask
  256. * @param int $depth Set the maximum depth. Must be greater than zero.
  257. *
  258. * @throws InvalidArgumentException if the JSON cannot be encoded.
  259. *
  260. * @link https://www.php.net/manual/en/function.json-encode.php
  261. */
  262. public static function jsonEncode($value, int $options = 0, int $depth = 512): string
  263. {
  264. $json = \json_encode($value, $options, $depth);
  265. if (\JSON_ERROR_NONE !== \json_last_error()) {
  266. throw new InvalidArgumentException('json_encode error: ' . \json_last_error_msg());
  267. }
  268. /** @var string */
  269. return $json;
  270. }
  271. /**
  272. * Wrapper for the hrtime() or microtime() functions
  273. * (depending on the PHP version, one of the two is used)
  274. *
  275. * @return float UNIX timestamp
  276. *
  277. * @internal
  278. */
  279. public static function currentTime(): float
  280. {
  281. return (float) \function_exists('hrtime') ? \hrtime(true) / 1e9 : \microtime(true);
  282. }
  283. /**
  284. * @throws InvalidArgumentException
  285. *
  286. * @internal
  287. */
  288. public static function idnUriConvert(UriInterface $uri, int $options = 0): UriInterface
  289. {
  290. if ($uri->getHost()) {
  291. $asciiHost = self::idnToAsci($uri->getHost(), $options, $info);
  292. if ($asciiHost === false) {
  293. $errorBitSet = $info['errors'] ?? 0;
  294. $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool {
  295. return substr($name, 0, 11) === 'IDNA_ERROR_';
  296. });
  297. $errors = [];
  298. foreach ($errorConstants as $errorConstant) {
  299. if ($errorBitSet & constant($errorConstant)) {
  300. $errors[] = $errorConstant;
  301. }
  302. }
  303. $errorMessage = 'IDN conversion failed';
  304. if ($errors) {
  305. $errorMessage .= ' (errors: ' . implode(', ', $errors) . ')';
  306. }
  307. throw new InvalidArgumentException($errorMessage);
  308. }
  309. if ($uri->getHost() !== $asciiHost) {
  310. // Replace URI only if the ASCII version is different
  311. $uri = $uri->withHost($asciiHost);
  312. }
  313. }
  314. return $uri;
  315. }
  316. /**
  317. * @internal
  318. */
  319. public static function getenv(string $name): ?string
  320. {
  321. if (isset($_SERVER[$name])) {
  322. return (string) $_SERVER[$name];
  323. }
  324. if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) {
  325. return (string) $value;
  326. }
  327. return null;
  328. }
  329. /**
  330. * @return string|false
  331. */
  332. private static function idnToAsci(string $domain, int $options, ?array &$info = [])
  333. {
  334. if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) {
  335. return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info);
  336. }
  337. throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old');
  338. }
  339. }