Stream.php 9.0 KB

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