StreamWrapper.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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\Response;
  11. use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
  12. use Symfony\Contracts\HttpClient\HttpClientInterface;
  13. use Symfony\Contracts\HttpClient\ResponseInterface;
  14. /**
  15. * Allows turning ResponseInterface instances to PHP streams.
  16. *
  17. * @author Nicolas Grekas <p@tchwork.com>
  18. */
  19. class StreamWrapper
  20. {
  21. /** @var resource|null */
  22. public $context;
  23. /**
  24. * @var \Symfony\Contracts\HttpClient\HttpClientInterface|\Symfony\Contracts\HttpClient\ResponseInterface
  25. */
  26. private $client;
  27. /**
  28. * @var \Symfony\Contracts\HttpClient\ResponseInterface
  29. */
  30. private $response;
  31. /** @var resource|string|null */
  32. private $content;
  33. /** @var resource|callable|null */
  34. private $handle;
  35. /**
  36. * @var bool
  37. */
  38. private $blocking = true;
  39. /**
  40. * @var float|null
  41. */
  42. private $timeout;
  43. /**
  44. * @var bool
  45. */
  46. private $eof = false;
  47. /**
  48. * @var int|null
  49. */
  50. private $offset = 0;
  51. /**
  52. * Creates a PHP stream resource from a ResponseInterface.
  53. *
  54. * @return resource
  55. * @param \Symfony\Contracts\HttpClient\ResponseInterface $response
  56. * @param \Symfony\Contracts\HttpClient\HttpClientInterface|null $client
  57. */
  58. public static function createResource($response, $client = null)
  59. {
  60. if ($response instanceof StreamableInterface) {
  61. $stack = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  62. if ($response !== ($stack[1]['object'] ?? null)) {
  63. return $response->toStream(false);
  64. }
  65. }
  66. if (null === $client && !method_exists($response, 'stream')) {
  67. throw new \InvalidArgumentException(sprintf('Providing a client to "%s()" is required when the response doesn\'t have any "stream()" method.', __CLASS__));
  68. }
  69. static $registered = false;
  70. if (!$registered = $registered || stream_wrapper_register(strtr(__CLASS__, '\\', '-'), __CLASS__)) {
  71. throw new \RuntimeException(error_get_last()['message'] ?? 'Registering the "symfony" stream wrapper failed.');
  72. }
  73. $context = [
  74. 'client' => $client ?? $response,
  75. 'response' => $response,
  76. ];
  77. return fopen(strtr(__CLASS__, '\\', '-').'://'.$response->getInfo('url'), 'r', false, stream_context_create(['symfony' => $context]));
  78. }
  79. public function getResponse()
  80. {
  81. return $this->response;
  82. }
  83. /**
  84. * @param resource|callable|null $handle The resource handle that should be monitored when
  85. * stream_select() is used on the created stream
  86. * @param resource|null $content The seekable resource where the response body is buffered
  87. */
  88. public function bindHandles(&$handle, &$content)
  89. {
  90. $this->handle = &$handle;
  91. $this->content = &$content;
  92. $this->offset = null;
  93. }
  94. /**
  95. * @param string $path
  96. * @param string $mode
  97. * @param int $options
  98. */
  99. public function stream_open($path, $mode, $options)
  100. {
  101. if ('r' !== $mode) {
  102. if ($options & \STREAM_REPORT_ERRORS) {
  103. trigger_error(sprintf('Invalid mode "%s": only "r" is supported.', $mode), \E_USER_WARNING);
  104. }
  105. return false;
  106. }
  107. $context = stream_context_get_options($this->context)['symfony'] ?? null;
  108. $this->client = $context['client'] ?? null;
  109. $this->response = $context['response'] ?? null;
  110. $this->context = null;
  111. if (null !== $this->client && null !== $this->response) {
  112. return true;
  113. }
  114. if ($options & \STREAM_REPORT_ERRORS) {
  115. trigger_error('Missing options "client" or "response" in "symfony" stream context.', \E_USER_WARNING);
  116. }
  117. return false;
  118. }
  119. /**
  120. * @return string|false
  121. * @param int $count
  122. */
  123. public function stream_read($count)
  124. {
  125. if (\is_resource($this->content)) {
  126. // Empty the internal activity list
  127. foreach ($this->client->stream([$this->response], 0) as $chunk) {
  128. try {
  129. if (!$chunk->isTimeout() && $chunk->isFirst()) {
  130. $this->response->getStatusCode(); // ignore 3/4/5xx
  131. }
  132. } catch (ExceptionInterface $e) {
  133. trigger_error($e->getMessage(), \E_USER_WARNING);
  134. return false;
  135. }
  136. }
  137. if (0 !== fseek($this->content, $this->offset ?? 0)) {
  138. return false;
  139. }
  140. if ('' !== $data = fread($this->content, $count)) {
  141. fseek($this->content, 0, \SEEK_END);
  142. $this->offset += \strlen($data);
  143. return $data;
  144. }
  145. }
  146. if (\is_string($this->content)) {
  147. if (\strlen($this->content) <= $count) {
  148. $data = $this->content;
  149. $this->content = null;
  150. } else {
  151. $data = substr($this->content, 0, $count);
  152. $this->content = substr($this->content, $count);
  153. }
  154. $this->offset += \strlen($data);
  155. return $data;
  156. }
  157. foreach ($this->client->stream([$this->response], $this->blocking ? $this->timeout : 0) as $chunk) {
  158. try {
  159. $this->eof = true;
  160. $this->eof = !$chunk->isTimeout();
  161. if (!$this->eof && !$this->blocking) {
  162. return '';
  163. }
  164. $this->eof = $chunk->isLast();
  165. if ($chunk->isFirst()) {
  166. $this->response->getStatusCode(); // ignore 3/4/5xx
  167. }
  168. if ('' !== $data = $chunk->getContent()) {
  169. if (\strlen($data) > $count) {
  170. $this->content = $this->content ?? substr($data, $count);
  171. $data = substr($data, 0, $count);
  172. }
  173. $this->offset += \strlen($data);
  174. return $data;
  175. }
  176. } catch (ExceptionInterface $e) {
  177. trigger_error($e->getMessage(), \E_USER_WARNING);
  178. return false;
  179. }
  180. }
  181. return '';
  182. }
  183. /**
  184. * @param int $option
  185. * @param int $arg1
  186. * @param int|null $arg2
  187. */
  188. public function stream_set_option($option, $arg1, $arg2)
  189. {
  190. if (\STREAM_OPTION_BLOCKING === $option) {
  191. $this->blocking = (bool) $arg1;
  192. } elseif (\STREAM_OPTION_READ_TIMEOUT === $option) {
  193. $this->timeout = $arg1 + $arg2 / 1e6;
  194. } else {
  195. return false;
  196. }
  197. return true;
  198. }
  199. public function stream_tell()
  200. {
  201. return $this->offset ?? 0;
  202. }
  203. public function stream_eof()
  204. {
  205. return $this->eof && !\is_string($this->content);
  206. }
  207. /**
  208. * @param int $offset
  209. * @param int $whence
  210. */
  211. public function stream_seek($offset, $whence = \SEEK_SET)
  212. {
  213. if (null === $this->content && null === $this->offset) {
  214. $this->response->getStatusCode();
  215. $this->offset = 0;
  216. }
  217. if (!\is_resource($this->content) || 0 !== fseek($this->content, 0, \SEEK_END)) {
  218. return false;
  219. }
  220. $size = ftell($this->content);
  221. if (\SEEK_CUR === $whence) {
  222. $offset += $this->offset ?? 0;
  223. }
  224. if (\SEEK_END === $whence || $size < $offset) {
  225. foreach ($this->client->stream([$this->response]) as $chunk) {
  226. try {
  227. if ($chunk->isFirst()) {
  228. $this->response->getStatusCode(); // ignore 3/4/5xx
  229. }
  230. // Chunks are buffered in $this->content already
  231. $size += \strlen($chunk->getContent());
  232. if (\SEEK_END !== $whence && $offset <= $size) {
  233. break;
  234. }
  235. } catch (ExceptionInterface $e) {
  236. trigger_error($e->getMessage(), \E_USER_WARNING);
  237. return false;
  238. }
  239. }
  240. if (\SEEK_END === $whence) {
  241. $offset += $size;
  242. }
  243. }
  244. if (0 <= $offset && $offset <= $size) {
  245. $this->eof = false;
  246. $this->offset = $offset;
  247. return true;
  248. }
  249. return false;
  250. }
  251. /**
  252. * @return resource|false
  253. * @param int $castAs
  254. */
  255. public function stream_cast($castAs)
  256. {
  257. if (\STREAM_CAST_FOR_SELECT === $castAs) {
  258. $this->response->getHeaders(false);
  259. return (\is_callable($this->handle) ? ($this->handle)() : $this->handle) ?? false;
  260. }
  261. return false;
  262. }
  263. public function stream_stat()
  264. {
  265. try {
  266. $headers = $this->response->getHeaders(false);
  267. } catch (ExceptionInterface $e) {
  268. trigger_error($e->getMessage(), \E_USER_WARNING);
  269. $headers = [];
  270. }
  271. return [
  272. 'dev' => 0,
  273. 'ino' => 0,
  274. 'mode' => 33060,
  275. 'nlink' => 0,
  276. 'uid' => 0,
  277. 'gid' => 0,
  278. 'rdev' => 0,
  279. 'size' => (int) ($headers['content-length'][0] ?? -1),
  280. 'atime' => 0,
  281. 'mtime' => strtotime($headers['last-modified'][0] ?? '') ?: 0,
  282. 'ctime' => 0,
  283. 'blksize' => 0,
  284. 'blocks' => 0,
  285. ];
  286. }
  287. private function __construct()
  288. {
  289. }
  290. }