PhpStreamRequestFactory.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. // Turn off error reporting while we try to initiate the request
  230. $level = error_reporting(0);
  231. $resource = call_user_func($callback);
  232. error_reporting($level);
  233. // If the resource could not be created, then grab the last error and throw an exception
  234. if (false === $resource) {
  235. $message = 'Error creating resource. ';
  236. foreach (error_get_last() as $key => $value) {
  237. $message .= "[{$key}] {$value} ";
  238. }
  239. throw new RuntimeException(trim($message));
  240. }
  241. return $resource;
  242. }
  243. }