DuplexResourceStream.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. <?php
  2. namespace React\Stream;
  3. use Evenement\EventEmitter;
  4. use React\EventLoop\Loop;
  5. use React\EventLoop\LoopInterface;
  6. use InvalidArgumentException;
  7. final class DuplexResourceStream extends EventEmitter implements DuplexStreamInterface
  8. {
  9. private $stream;
  10. /** @var LoopInterface */
  11. private $loop;
  12. /**
  13. * Controls the maximum buffer size in bytes to read at once from the stream.
  14. *
  15. * This can be a positive number which means that up to X bytes will be read
  16. * at once from the underlying stream resource. Note that the actual number
  17. * of bytes read may be lower if the stream resource has less than X bytes
  18. * currently available.
  19. *
  20. * This can be `-1` which means read everything available from the
  21. * underlying stream resource.
  22. * This should read until the stream resource is not readable anymore
  23. * (i.e. underlying buffer drained), note that this does not neccessarily
  24. * mean it reached EOF.
  25. *
  26. * @var int
  27. */
  28. private $bufferSize;
  29. private $buffer;
  30. private $readable = true;
  31. private $writable = true;
  32. private $closing = false;
  33. private $listening = false;
  34. public function __construct($stream, LoopInterface $loop = null, $readChunkSize = null, WritableStreamInterface $buffer = null)
  35. {
  36. if (!\is_resource($stream) || \get_resource_type($stream) !== "stream") {
  37. throw new InvalidArgumentException('First parameter must be a valid stream resource');
  38. }
  39. // ensure resource is opened for reading and wrting (fopen mode must contain "+")
  40. $meta = \stream_get_meta_data($stream);
  41. if (isset($meta['mode']) && $meta['mode'] !== '' && \strpos($meta['mode'], '+') === false) {
  42. throw new InvalidArgumentException('Given stream resource is not opened in read and write mode');
  43. }
  44. // this class relies on non-blocking I/O in order to not interrupt the event loop
  45. // e.g. pipes on Windows do not support this: https://bugs.php.net/bug.php?id=47918
  46. if ($buffer !== null && !$buffer instanceof WritableResourceStream && \stream_set_blocking($stream, false) !== true) {
  47. throw new \RuntimeException('Unable to set stream resource to non-blocking mode');
  48. }
  49. // Use unbuffered read operations on the underlying stream resource.
  50. // Reading chunks from the stream may otherwise leave unread bytes in
  51. // PHP's stream buffers which some event loop implementations do not
  52. // trigger events on (edge triggered).
  53. // This does not affect the default event loop implementation (level
  54. // triggered), so we can ignore platforms not supporting this (HHVM).
  55. // Pipe streams (such as STDIN) do not seem to require this and legacy
  56. // PHP versions cause SEGFAULTs on unbuffered pipe streams, so skip this.
  57. if (\function_exists('stream_set_read_buffer') && !$this->isLegacyPipe($stream)) {
  58. \stream_set_read_buffer($stream, 0);
  59. }
  60. if ($buffer === null) {
  61. $buffer = new WritableResourceStream($stream, $loop);
  62. }
  63. $this->stream = $stream;
  64. $this->loop = $loop ?: Loop::get();
  65. $this->bufferSize = ($readChunkSize === null) ? 65536 : (int)$readChunkSize;
  66. $this->buffer = $buffer;
  67. $that = $this;
  68. $this->buffer->on('error', function ($error) use ($that) {
  69. $that->emit('error', array($error));
  70. });
  71. $this->buffer->on('close', array($this, 'close'));
  72. $this->buffer->on('drain', function () use ($that) {
  73. $that->emit('drain');
  74. });
  75. $this->resume();
  76. }
  77. public function isReadable()
  78. {
  79. return $this->readable;
  80. }
  81. public function isWritable()
  82. {
  83. return $this->writable;
  84. }
  85. public function pause()
  86. {
  87. if ($this->listening) {
  88. $this->loop->removeReadStream($this->stream);
  89. $this->listening = false;
  90. }
  91. }
  92. public function resume()
  93. {
  94. if (!$this->listening && $this->readable) {
  95. $this->loop->addReadStream($this->stream, array($this, 'handleData'));
  96. $this->listening = true;
  97. }
  98. }
  99. public function write($data)
  100. {
  101. if (!$this->writable) {
  102. return false;
  103. }
  104. return $this->buffer->write($data);
  105. }
  106. public function close()
  107. {
  108. if (!$this->writable && !$this->closing) {
  109. return;
  110. }
  111. $this->closing = false;
  112. $this->readable = false;
  113. $this->writable = false;
  114. $this->emit('close');
  115. $this->pause();
  116. $this->buffer->close();
  117. $this->removeAllListeners();
  118. if (\is_resource($this->stream)) {
  119. \fclose($this->stream);
  120. }
  121. }
  122. public function end($data = null)
  123. {
  124. if (!$this->writable) {
  125. return;
  126. }
  127. $this->closing = true;
  128. $this->readable = false;
  129. $this->writable = false;
  130. $this->pause();
  131. $this->buffer->end($data);
  132. }
  133. public function pipe(WritableStreamInterface $dest, array $options = array())
  134. {
  135. return Util::pipe($this, $dest, $options);
  136. }
  137. /** @internal */
  138. public function handleData($stream)
  139. {
  140. $error = null;
  141. \set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$error) {
  142. $error = new \ErrorException(
  143. $errstr,
  144. 0,
  145. $errno,
  146. $errfile,
  147. $errline
  148. );
  149. });
  150. $data = \stream_get_contents($stream, $this->bufferSize);
  151. \restore_error_handler();
  152. if ($error !== null) {
  153. $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error)));
  154. $this->close();
  155. return;
  156. }
  157. if ($data !== '') {
  158. $this->emit('data', array($data));
  159. } elseif (\feof($this->stream)) {
  160. // no data read => we reached the end and close the stream
  161. $this->emit('end');
  162. $this->close();
  163. }
  164. }
  165. /**
  166. * Returns whether this is a pipe resource in a legacy environment
  167. *
  168. * This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+
  169. * and PHP 5.5.12+ and newer.
  170. *
  171. * @param resource $resource
  172. * @return bool
  173. * @link https://github.com/reactphp/child-process/issues/40
  174. *
  175. * @codeCoverageIgnore
  176. */
  177. private function isLegacyPipe($resource)
  178. {
  179. if (\PHP_VERSION_ID < 50428 || (\PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512)) {
  180. $meta = \stream_get_meta_data($resource);
  181. if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') {
  182. return true;
  183. }
  184. }
  185. return false;
  186. }
  187. }