PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/guzzlehttp/guzzle/src/functions.php

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