Stream.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. $contents = stream_get_contents($this->stream);
  88. if ($contents === false) {
  89. throw new \RuntimeException('Unable to read stream contents');
  90. }
  91. return $contents;
  92. }
  93. public function close(): void
  94. {
  95. if (isset($this->stream)) {
  96. if (is_resource($this->stream)) {
  97. fclose($this->stream);
  98. }
  99. $this->detach();
  100. }
  101. }
  102. public function detach()
  103. {
  104. if (!isset($this->stream)) {
  105. return null;
  106. }
  107. $result = $this->stream;
  108. unset($this->stream);
  109. $this->size = $this->uri = null;
  110. $this->readable = $this->writable = $this->seekable = false;
  111. return $result;
  112. }
  113. public function getSize(): ?int
  114. {
  115. if ($this->size !== null) {
  116. return $this->size;
  117. }
  118. if (!isset($this->stream)) {
  119. return null;
  120. }
  121. // Clear the stat cache if the stream has a URI
  122. if ($this->uri) {
  123. clearstatcache(true, $this->uri);
  124. }
  125. $stats = fstat($this->stream);
  126. if (is_array($stats) && isset($stats['size'])) {
  127. $this->size = $stats['size'];
  128. return $this->size;
  129. }
  130. return null;
  131. }
  132. public function isReadable(): bool
  133. {
  134. return $this->readable;
  135. }
  136. public function isWritable(): bool
  137. {
  138. return $this->writable;
  139. }
  140. public function isSeekable(): bool
  141. {
  142. return $this->seekable;
  143. }
  144. public function eof(): bool
  145. {
  146. if (!isset($this->stream)) {
  147. throw new \RuntimeException('Stream is detached');
  148. }
  149. return feof($this->stream);
  150. }
  151. public function tell(): int
  152. {
  153. if (!isset($this->stream)) {
  154. throw new \RuntimeException('Stream is detached');
  155. }
  156. $result = ftell($this->stream);
  157. if ($result === false) {
  158. throw new \RuntimeException('Unable to determine stream position');
  159. }
  160. return $result;
  161. }
  162. public function rewind(): void
  163. {
  164. $this->seek(0);
  165. }
  166. public function seek($offset, $whence = SEEK_SET): void
  167. {
  168. $whence = (int) $whence;
  169. if (!isset($this->stream)) {
  170. throw new \RuntimeException('Stream is detached');
  171. }
  172. if (!$this->seekable) {
  173. throw new \RuntimeException('Stream is not seekable');
  174. }
  175. if (fseek($this->stream, $offset, $whence) === -1) {
  176. throw new \RuntimeException('Unable to seek to stream position '
  177. . $offset . ' with whence ' . var_export($whence, true));
  178. }
  179. }
  180. public function read($length): string
  181. {
  182. if (!isset($this->stream)) {
  183. throw new \RuntimeException('Stream is detached');
  184. }
  185. if (!$this->readable) {
  186. throw new \RuntimeException('Cannot read from non-readable stream');
  187. }
  188. if ($length < 0) {
  189. throw new \RuntimeException('Length parameter cannot be negative');
  190. }
  191. if (0 === $length) {
  192. return '';
  193. }
  194. $string = fread($this->stream, $length);
  195. if (false === $string) {
  196. throw new \RuntimeException('Unable to read from stream');
  197. }
  198. return $string;
  199. }
  200. public function write($string): int
  201. {
  202. if (!isset($this->stream)) {
  203. throw new \RuntimeException('Stream is detached');
  204. }
  205. if (!$this->writable) {
  206. throw new \RuntimeException('Cannot write to a non-writable stream');
  207. }
  208. // We can't know the size after writing anything
  209. $this->size = null;
  210. $result = fwrite($this->stream, $string);
  211. if ($result === false) {
  212. throw new \RuntimeException('Unable to write to stream');
  213. }
  214. return $result;
  215. }
  216. /**
  217. * {@inheritdoc}
  218. *
  219. * @return mixed
  220. */
  221. public function getMetadata($key = null)
  222. {
  223. if (!isset($this->stream)) {
  224. return $key ? null : [];
  225. } elseif (!$key) {
  226. return $this->customMetadata + stream_get_meta_data($this->stream);
  227. } elseif (isset($this->customMetadata[$key])) {
  228. return $this->customMetadata[$key];
  229. }
  230. $meta = stream_get_meta_data($this->stream);
  231. return $meta[$key] ?? null;
  232. }
  233. }