Debian Codegraph @

vendor/react/stream/src/ReadableResourceStream.php

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