FileStream.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. namespace Yurun\Util\YurunHttp\Stream;
  3. use Psr\Http\Message\StreamInterface;
  4. use Psr\Http\Message\UriInterface;
  5. use Yurun\Util\YurunHttp\Http\Psr7\Uri;
  6. class FileStream implements StreamInterface
  7. {
  8. /**
  9. * 文件Uri.
  10. *
  11. * @var UriInterface
  12. */
  13. protected $uri;
  14. /**
  15. * 流对象
  16. *
  17. * @var resource|null
  18. */
  19. protected $stream;
  20. /**
  21. * 流访问类型.
  22. *
  23. * @var string
  24. */
  25. protected $mode;
  26. /**
  27. * @param string|UriInterface $uri
  28. * @param string $mode
  29. */
  30. public function __construct($uri, $mode = StreamMode::READ_WRITE)
  31. {
  32. if (\is_string($uri))
  33. {
  34. $this->uri = $uri = new Uri($uri);
  35. }
  36. elseif ($uri instanceof UriInterface)
  37. {
  38. $this->uri = $uri;
  39. }
  40. else
  41. {
  42. $uri = $this->uri;
  43. }
  44. $this->mode = $mode;
  45. $stream = fopen($uri, $mode);
  46. if (false === $stream)
  47. {
  48. throw new \RuntimeException(sprintf('Open stream %s error', (string) $uri));
  49. }
  50. $this->stream = $stream;
  51. }
  52. public function __destruct()
  53. {
  54. if ($this->stream)
  55. {
  56. $this->close();
  57. }
  58. }
  59. /**
  60. * Reads all data from the stream into a string, from the beginning to end.
  61. *
  62. * This method MUST attempt to seek to the beginning of the stream before
  63. * reading data and read the stream until the end is reached.
  64. *
  65. * Warning: This could attempt to load a large amount of data into memory.
  66. *
  67. * This method MUST NOT raise an exception in order to conform with PHP's
  68. * string casting operations.
  69. *
  70. * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
  71. *
  72. * @return string
  73. */
  74. public function __toString()
  75. {
  76. try
  77. {
  78. $this->rewind();
  79. return stream_get_contents($this->stream);
  80. }
  81. catch (\Throwable $ex)
  82. {
  83. return '';
  84. }
  85. }
  86. /**
  87. * Closes the stream and any underlying resources.
  88. *
  89. * @return void
  90. */
  91. public function close()
  92. {
  93. fclose($this->stream);
  94. $this->stream = null;
  95. }
  96. /**
  97. * Separates any underlying resources from the stream.
  98. *
  99. * After the stream has been detached, the stream is in an unusable state.
  100. *
  101. * @return resource|null Underlying PHP stream, if any
  102. */
  103. public function detach()
  104. {
  105. $stream = $this->stream;
  106. $this->stream = null;
  107. return $stream;
  108. }
  109. /**
  110. * Get the size of the stream if known.
  111. *
  112. * @return int|null returns the size in bytes if known, or null if unknown
  113. */
  114. public function getSize()
  115. {
  116. $stat = fstat($this->stream);
  117. if (false === $stat)
  118. {
  119. throw new \RuntimeException('get stream size error');
  120. }
  121. return $stat['size'];
  122. }
  123. /**
  124. * Returns the current position of the file read/write pointer.
  125. *
  126. * @return int Position of the file pointer
  127. *
  128. * @throws \RuntimeException on error
  129. */
  130. public function tell()
  131. {
  132. $result = ftell($this->stream);
  133. if (false === $result)
  134. {
  135. throw new \RuntimeException('stream tell error');
  136. }
  137. return $result;
  138. }
  139. /**
  140. * Returns true if the stream is at the end of the stream.
  141. *
  142. * @return bool
  143. */
  144. public function eof()
  145. {
  146. return feof($this->stream);
  147. }
  148. /**
  149. * Returns whether or not the stream is seekable.
  150. *
  151. * @return bool
  152. */
  153. public function isSeekable()
  154. {
  155. return (bool) $this->getMetadata('seekable');
  156. }
  157. /**
  158. * Seek to a position in the stream.
  159. *
  160. * @see http://www.php.net/manual/en/function.fseek.php
  161. *
  162. * @param int $offset Stream offset
  163. * @param int $whence Specifies how the cursor position will be calculated
  164. * based on the seek offset. Valid values are identical to the built-in
  165. * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
  166. * offset bytes SEEK_CUR: Set position to current location plus offset
  167. * SEEK_END: Set position to end-of-stream plus offset.
  168. *
  169. * @return void
  170. *
  171. * @throws \RuntimeException on failure
  172. */
  173. public function seek($offset, $whence = \SEEK_SET)
  174. {
  175. if (-1 === fseek($this->stream, $offset, $whence))
  176. {
  177. throw new \RuntimeException('seek stream error');
  178. }
  179. }
  180. /**
  181. * Seek to the beginning of the stream.
  182. *
  183. * If the stream is not seekable, this method will raise an exception;
  184. * otherwise, it will perform a seek(0).
  185. *
  186. * @see seek()
  187. * @see http://www.php.net/manual/en/function.fseek.php
  188. *
  189. * @return void
  190. *
  191. * @throws \RuntimeException on failure
  192. */
  193. public function rewind()
  194. {
  195. if (!rewind($this->stream))
  196. {
  197. throw new \RuntimeException('rewind stream failed');
  198. }
  199. }
  200. /**
  201. * Returns whether or not the stream is writable.
  202. *
  203. * @return bool
  204. */
  205. public function isWritable()
  206. {
  207. return \in_array($this->mode, [
  208. StreamMode::WRITE_CLEAN,
  209. StreamMode::WRITE_END,
  210. StreamMode::CREATE_READ_WRITE,
  211. StreamMode::CREATE_WRITE,
  212. StreamMode::READ_WRITE,
  213. StreamMode::READ_WRITE_CLEAN,
  214. StreamMode::READ_WRITE_END,
  215. ]);
  216. }
  217. /**
  218. * Write data to the stream.
  219. *
  220. * @param string $string the string that is to be written
  221. *
  222. * @return int returns the number of bytes written to the stream
  223. *
  224. * @throws \RuntimeException on failure
  225. */
  226. public function write($string)
  227. {
  228. $result = fwrite($this->stream, $string);
  229. if (false === $result)
  230. {
  231. throw new \RuntimeException('write stream failed');
  232. }
  233. return $result;
  234. }
  235. /**
  236. * Returns whether or not the stream is readable.
  237. *
  238. * @return bool
  239. */
  240. public function isReadable()
  241. {
  242. return \in_array($this->mode, [
  243. StreamMode::READ_WRITE,
  244. StreamMode::READ_WRITE_CLEAN,
  245. StreamMode::READ_WRITE_END,
  246. StreamMode::READONLY,
  247. StreamMode::CREATE_READ_WRITE,
  248. ]);
  249. }
  250. /**
  251. * Read data from the stream.
  252. *
  253. * @param int $length Read up to $length bytes from the object and return
  254. * them. Fewer than $length bytes may be returned if underlying stream
  255. * call returns fewer bytes.
  256. *
  257. * @return string returns the data read from the stream, or an empty string
  258. * if no bytes are available
  259. *
  260. * @throws \RuntimeException if an error occurs
  261. */
  262. public function read($length)
  263. {
  264. $result = fread($this->stream, $length);
  265. if (false === $result)
  266. {
  267. throw new \RuntimeException('read stream error');
  268. }
  269. return $result;
  270. }
  271. /**
  272. * Returns the remaining contents in a string.
  273. *
  274. * @return string
  275. *
  276. * @throws \RuntimeException if unable to read or an error occurs while
  277. * reading
  278. */
  279. public function getContents()
  280. {
  281. $result = stream_get_contents($this->stream);
  282. if (false === $result)
  283. {
  284. throw new \RuntimeException('stream getContents error');
  285. }
  286. return $result;
  287. }
  288. /**
  289. * Get stream metadata as an associative array or retrieve a specific key.
  290. *
  291. * The keys returned are identical to the keys returned from PHP's
  292. * stream_get_meta_data() function.
  293. *
  294. * @see http://php.net/manual/en/function.stream-get-meta-data.php
  295. *
  296. * @param string $key specific metadata to retrieve
  297. *
  298. * @return array|mixed|null Returns an associative array if no key is
  299. * provided. Returns a specific key value if a key is provided and the
  300. * value is found, or null if the key is not found.
  301. */
  302. public function getMetadata($key = null)
  303. {
  304. $result = stream_get_meta_data($this->stream);
  305. /* @phpstan-ignore-next-line */
  306. if (!$result)
  307. {
  308. throw new \RuntimeException('stream getMetadata error');
  309. }
  310. if (null === $key)
  311. {
  312. return $result;
  313. }
  314. elseif (isset($result[$key]))
  315. {
  316. return $result[$key];
  317. }
  318. else
  319. {
  320. return null;
  321. }
  322. }
  323. /**
  324. * Get Uri.
  325. *
  326. * @return UriInterface
  327. */
  328. public function getUri()
  329. {
  330. return $this->uri;
  331. }
  332. }