PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/iwp-client/lib/amazon/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php

https://gitlab.com/treighton/wpgit
PHP | 284 lines | 162 code | 33 blank | 89 comment | 17 complexity | bdc6ccb3c2456ad8392bceb6cb9f6838 MD5 | raw file
  1. <?php
  2. namespace Guzzle\Stream;
  3. use Guzzle\Common\Exception\InvalidArgumentException;
  4. use Guzzle\Common\Exception\RuntimeException;
  5. use Guzzle\Http\Message\EntityEnclosingRequestInterface;
  6. use Guzzle\Http\Message\RequestInterface;
  7. use Guzzle\Http\Url;
  8. /**
  9. * Factory used to create fopen streams using PHP's http and https stream wrappers
  10. *
  11. * Note: PHP's http stream wrapper only supports streaming downloads. It does not support streaming uploads.
  12. */
  13. class PhpStreamRequestFactory implements StreamRequestFactoryInterface
  14. {
  15. /** @var resource Stream context options */
  16. protected $context;
  17. /** @var array Stream context */
  18. protected $contextOptions;
  19. /** @var Url Stream URL */
  20. protected $url;
  21. /** @var array Last response headers received by the HTTP request */
  22. protected $lastResponseHeaders;
  23. /**
  24. * {@inheritdoc}
  25. *
  26. * The $params array can contain the following custom keys specific to the PhpStreamRequestFactory:
  27. * - stream_class: The name of a class to create instead of a Guzzle\Stream\Stream object
  28. */
  29. public function fromRequest(RequestInterface $request, $context = array(), array $params = array())
  30. {
  31. if (is_resource($context)) {
  32. $this->contextOptions = stream_context_get_options($context);
  33. $this->context = $context;
  34. } elseif (is_array($context) || !$context) {
  35. $this->contextOptions = $context;
  36. $this->createContext($params);
  37. } elseif ($context) {
  38. throw new InvalidArgumentException('$context must be an array or resource');
  39. }
  40. // Dispatch the before send event
  41. $request->dispatch('request.before_send', array(
  42. 'request' => $request,
  43. 'context' => $this->context,
  44. 'context_options' => $this->contextOptions
  45. ));
  46. $this->setUrl($request);
  47. $this->addDefaultContextOptions($request);
  48. $this->addSslOptions($request);
  49. $this->addBodyOptions($request);
  50. $this->addProxyOptions($request);
  51. // Create the file handle but silence errors
  52. return $this->createStream($params)
  53. ->setCustomData('request', $request)
  54. ->setCustomData('response_headers', $this->getLastResponseHeaders());
  55. }
  56. /**
  57. * Set an option on the context and the internal options array
  58. *
  59. * @param string $wrapper Stream wrapper name of http
  60. * @param string $name Context name
  61. * @param mixed $value Context value
  62. * @param bool $overwrite Set to true to overwrite an existing value
  63. */
  64. protected function setContextValue($wrapper, $name, $value, $overwrite = false)
  65. {
  66. if (!isset($this->contextOptions[$wrapper])) {
  67. $this->contextOptions[$wrapper] = array($name => $value);
  68. } elseif (!$overwrite && isset($this->contextOptions[$wrapper][$name])) {
  69. return;
  70. }
  71. $this->contextOptions[$wrapper][$name] = $value;
  72. stream_context_set_option($this->context, $wrapper, $name, $value);
  73. }
  74. /**
  75. * Create a stream context
  76. *
  77. * @param array $params Parameter array
  78. */
  79. protected function createContext(array $params)
  80. {
  81. $options = $this->contextOptions;
  82. $this->context = $this->createResource(function () use ($params, $options) {
  83. return stream_context_create($options, $params);
  84. });
  85. }
  86. /**
  87. * Get the last response headers received by the HTTP request
  88. *
  89. * @return array
  90. */
  91. public function getLastResponseHeaders()
  92. {
  93. return $this->lastResponseHeaders;
  94. }
  95. /**
  96. * Adds the default context options to the stream context options
  97. *
  98. * @param RequestInterface $request Request
  99. */
  100. protected function addDefaultContextOptions(RequestInterface $request)
  101. {
  102. $this->setContextValue('http', 'method', $request->getMethod());
  103. $headers = $request->getHeaderLines();
  104. // "Connection: close" is required to get streams to work in HTTP 1.1
  105. if (!$request->hasHeader('Connection')) {
  106. $headers[] = 'Connection: close';
  107. }
  108. $this->setContextValue('http', 'header', $headers);
  109. $this->setContextValue('http', 'protocol_version', $request->getProtocolVersion());
  110. $this->setContextValue('http', 'ignore_errors', true);
  111. }
  112. /**
  113. * Set the URL to use with the factory
  114. *
  115. * @param RequestInterface $request Request that owns the URL
  116. */
  117. protected function setUrl(RequestInterface $request)
  118. {
  119. $this->url = $request->getUrl(true);
  120. // Check for basic Auth username
  121. if ($request->getUsername()) {
  122. $this->url->setUsername($request->getUsername());
  123. }
  124. // Check for basic Auth password
  125. if ($request->getPassword()) {
  126. $this->url->setPassword($request->getPassword());
  127. }
  128. }
  129. /**
  130. * Add SSL options to the stream context
  131. *
  132. * @param RequestInterface $request Request
  133. */
  134. protected function addSslOptions(RequestInterface $request)
  135. {
  136. if ($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)) {
  137. $this->setContextValue('ssl', 'verify_peer', true, true);
  138. if ($cafile = $request->getCurlOptions()->get(CURLOPT_CAINFO)) {
  139. $this->setContextValue('ssl', 'cafile', $cafile, true);
  140. }
  141. } else {
  142. $this->setContextValue('ssl', 'verify_peer', false, true);
  143. }
  144. }
  145. /**
  146. * Add body (content) specific options to the context options
  147. *
  148. * @param RequestInterface $request
  149. */
  150. protected function addBodyOptions(RequestInterface $request)
  151. {
  152. // Add the content for the request if needed
  153. if (!($request instanceof EntityEnclosingRequestInterface)) {
  154. return;
  155. }
  156. if (count($request->getPostFields())) {
  157. $this->setContextValue('http', 'content', (string) $request->getPostFields(), true);
  158. } elseif ($request->getBody()) {
  159. $this->setContextValue('http', 'content', (string) $request->getBody(), true);
  160. }
  161. // Always ensure a content-length header is sent
  162. if (isset($this->contextOptions['http']['content'])) {
  163. $headers = isset($this->contextOptions['http']['header']) ? $this->contextOptions['http']['header'] : array();
  164. $headers[] = 'Content-Length: ' . strlen($this->contextOptions['http']['content']);
  165. $this->setContextValue('http', 'header', $headers, true);
  166. }
  167. }
  168. /**
  169. * Add proxy parameters to the context if needed
  170. *
  171. * @param RequestInterface $request Request
  172. */
  173. protected function addProxyOptions(RequestInterface $request)
  174. {
  175. if ($proxy = $request->getCurlOptions()->get(CURLOPT_PROXY)) {
  176. $this->setContextValue('http', 'proxy', $proxy);
  177. }
  178. }
  179. /**
  180. * Create the stream for the request with the context options
  181. *
  182. * @param array $params Parameters of the stream
  183. *
  184. * @return StreamInterface
  185. */
  186. protected function createStream(array $params)
  187. {
  188. $http_response_header = null;
  189. $url = $this->url;
  190. $context = $this->context;
  191. $fp = $this->createResource(function () use ($context, $url, &$http_response_header) {
  192. return fopen((string) $url, 'r', false, $context);
  193. });
  194. // Determine the class to instantiate
  195. $className = isset($params['stream_class']) ? $params['stream_class'] : __NAMESPACE__ . '\\Stream';
  196. /** @var $stream StreamInterface */
  197. $stream = new $className($fp);
  198. // Track the response headers of the request
  199. if (isset($http_response_header)) {
  200. $this->lastResponseHeaders = $http_response_header;
  201. $this->processResponseHeaders($stream);
  202. }
  203. return $stream;
  204. }
  205. /**
  206. * Process response headers
  207. *
  208. * @param StreamInterface $stream
  209. */
  210. protected function processResponseHeaders(StreamInterface $stream)
  211. {
  212. // Set the size on the stream if it was returned in the response
  213. foreach ($this->lastResponseHeaders as $header) {
  214. if ((stripos($header, 'Content-Length:')) === 0) {
  215. $stream->setSize(trim(substr($header, 15)));
  216. }
  217. }
  218. }
  219. /**
  220. * Create a resource and check to ensure it was created successfully
  221. *
  222. * @param callable $callback Closure to invoke that must return a valid resource
  223. *
  224. * @return resource
  225. * @throws RuntimeException on error
  226. */
  227. protected function createResource($callback)
  228. {
  229. $errors = null;
  230. set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
  231. $errors[] = array(
  232. 'message' => $msg,
  233. 'file' => $file,
  234. 'line' => $line
  235. );
  236. return true;
  237. });
  238. $resource = call_user_func($callback);
  239. restore_error_handler();
  240. if (!$resource) {
  241. $message = 'Error creating resource. ';
  242. foreach ($errors as $err) {
  243. foreach ($err as $key => $value) {
  244. $message .= "[$key] $value" . PHP_EOL;
  245. }
  246. }
  247. throw new RuntimeException(trim($message));
  248. }
  249. return $resource;
  250. }
  251. }