Stream.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\StreamInterface;
  5. /**
  6. * PHP stream implementation.
  7. */
  8. class Stream implements StreamInterface
  9. {
  10. /**
  11. * @see http://php.net/manual/function.fopen.php
  12. * @see http://php.net/manual/en/function.gzopen.php
  13. */
  14. private const READABLE_MODES = '/r|a\+|ab\+|w\+|wb\+|x\+|xb\+|c\+|cb\+/';
  15. private const WRITABLE_MODES = '/a|w|r\+|rb\+|rw|x|c/';
  16. /** @var resource */
  17. private $stream;
  18. /** @var int|null */
  19. private $size;
  20. /** @var bool */
  21. private $seekable;
  22. /** @var bool */
  23. private $readable;
  24. /** @var bool */
  25. private $writable;
  26. /** @var string|null */
  27. private $uri;
  28. /** @var mixed[] */
  29. private $customMetadata;
  30. /**
  31. * This constructor accepts an associative array of options.
  32. *
  33. * - size: (int) If a read stream would otherwise have an indeterminate
  34. * size, but the size is known due to foreknowledge, then you can
  35. * provide that size, in bytes.
  36. * - metadata: (array) Any additional metadata to return when the metadata
  37. * of the stream is accessed.
  38. *
  39. * @param resource $stream Stream resource to wrap.
  40. * @param array{size?: int, metadata?: array} $options Associative array of options.
  41. *
  42. * @throws \InvalidArgumentException if the stream is not a stream resource
  43. */
  44. public function __construct($stream, array $options = [])
  45. {
  46. if (!is_resource($stream)) {
  47. throw new \InvalidArgumentException('Stream must be a resource');
  48. }
  49. if (isset($options['size'])) {
  50. $this->size = $options['size'];
  51. }
  52. $this->customMetadata = $options['metadata'] ?? [];
  53. $this->stream = $stream;
  54. $meta = stream_get_meta_data($this->stream);
  55. $this->seekable = $meta['seekable'];
  56. $this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']);
  57. $this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']);
  58. $this->uri = $this->getMetadata('uri');
  59. }
  60. /**
  61. * Closes the stream when the destructed
  62. */
  63. public function __destruct()
  64. {
  65. $this->close();
  66. }
  67. public function __toString(): string
  68. {
  69. try {
  70. if ($this->isSeekable()) {
  71. $this->seek(0);
  72. }
  73. return $this->getContents();
  74. } catch (\Throwable $e) {
  75. if (\PHP_VERSION_ID >= 70400) {
  76. throw $e;
  77. }
  78. trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR);
  79. return '';
  80. }
  81. }
  82. public function getContents(): string
  83. {
  84. if (!isset($this->stream)) {
  85. throw new \RuntimeException('Stream is detached');
  86. }
  87. if (!$this->readable) {
  88. throw new \RuntimeException('Cannot read from non-readable stream');
  89. }
  90. return Utils::tryGetContents($this->stream);
  91. }
  92. public function close(): void
  93. {
  94. if (isset($this->stream)) {
  95. if (is_resource($this->stream)) {
  96. fclose($this->stream);
  97. }
  98. $this->detach();
  99. }
  100. }
  101. public function detach()
  102. {
  103. if (!isset($this->stream)) {
  104. return null;
  105. }
  106. $result = $this->stream;
  107. unset($this->stream);
  108. $this->size = $this->uri = null;
  109. $this->readable = $this->writable = $this->seekable = false;
  110. return $result;
  111. }
  112. public function getSize(): ?int
  113. {
  114. if ($this->size !== null) {
  115. return $this->size;
  116. }
  117. if (!isset($this->stream)) {
  118. return null;
  119. }
  120. // Clear the stat cache if the stream has a URI
  121. if ($this->uri) {
  122. clearstatcache(true, $this->uri);
  123. }
  124. $stats = fstat($this->stream);
  125. if (is_array($stats) && isset($stats['size'])) {
  126. $this->size = $stats['size'];
  127. return $this->size;
  128. }
  129. return null;
  130. }
  131. public function isReadable(): bool
  132. {
  133. return $this->readable;
  134. }
  135. public function isWritable(): bool
  136. {
  137. return $this->writable;
  138. }
  139. public function isSeekable(): bool
  140. {
  141. return $this->seekable;
  142. }
  143. public function eof(): bool
  144. {
  145. if (!isset($this->stream)) {
  146. throw new \RuntimeException('Stream is detached');
  147. }
  148. return feof($this->stream);
  149. }
  150. public function tell(): int
  151. {
  152. if (!isset($this->stream)) {
  153. throw new \RuntimeException('Stream is detached');
  154. }
  155. $result = ftell($this->stream);
  156. if ($result === false) {
  157. throw new \RuntimeException('Unable to determine stream position');
  158. }
  159. return $result;
  160. }
  161. public function rewind(): void
  162. {
  163. $this->seek(0);
  164. }
  165. public function seek($offset, $whence = SEEK_SET): void
  166. {
  167. $whence = (int) $whence;
  168. if (!isset($this->stream)) {
  169. throw new \RuntimeException('Stream is detached');
  170. }
  171. if (!$this->seekable) {
  172. throw new \RuntimeException('Stream is not seekable');
  173. }
  174. if (fseek($this->stream, $offset, $whence) === -1) {
  175. throw new \RuntimeException('Unable to seek to stream position '
  176. . $offset . ' with whence ' . var_export($whence, true));
  177. }
  178. }
  179. public function read($length): string
  180. {
  181. if (!isset($this->stream)) {
  182. throw new \RuntimeException('Stream is detached');
  183. }
  184. if (!$this->readable) {
  185. throw new \RuntimeException('Cannot read from non-readable stream');
  186. }
  187. if ($length < 0) {
  188. throw new \RuntimeException('Length parameter cannot be negative');
  189. }
  190. if (0 === $length) {
  191. return '';
  192. }
  193. try {
  194. $string = fread($this->stream, $length);
  195. } catch (\Exception $e) {
  196. throw new \RuntimeException('Unable to read from stream', 0, $e);
  197. }
  198. if (false === $string) {
  199. throw new \RuntimeException('Unable to read from stream');
  200. }
  201. return $string;
  202. }
  203. public function write($string): int
  204. {
  205. if (!isset($this->stream)) {
  206. throw new \RuntimeException('Stream is detached');
  207. }
  208. if (!$this->writable) {
  209. throw new \RuntimeException('Cannot write to a non-writable stream');
  210. }
  211. // We can't know the size after writing anything
  212. $this->size = null;
  213. $result = fwrite($this->stream, $string);
  214. if ($result === false) {
  215. throw new \RuntimeException('Unable to write to stream');
  216. }
  217. return $result;
  218. }
  219. /**
  220. * {@inheritdoc}
  221. *
  222. * @return mixed
  223. */
  224. public function getMetadata($key = null)
  225. {
  226. if (!isset($this->stream)) {
  227. return $key ? null : [];
  228. } elseif (!$key) {
  229. return $this->customMetadata + stream_get_meta_data($this->stream);
  230. } elseif (isset($this->customMetadata[$key])) {
  231. return $this->customMetadata[$key];
  232. }
  233. $meta = stream_get_meta_data($this->stream);
  234. return $meta[$key] ?? null;
  235. }
  236. }