Skip to content

Commit f2f9b2e

Browse files
authored
Merge pull request #4 from cloudtay/fix-feof-after-close
Fix: prevent fatal error when calling feof after close
2 parents 7b8bb0a + c85abb4 commit f2f9b2e

1 file changed

Lines changed: 19 additions & 18 deletions

File tree

src/Server/Response.php

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,12 @@
1717
use Ripple\Socket;
1818
use Ripple\Stream;
1919
use Ripple\Stream\Exception\ConnectionException;
20+
use Ripple\WaitGroup;
21+
use RuntimeException;
2022
use Throwable;
2123

2224
use function basename;
25+
use function Co\go;
2326
use function Co\promise;
2427
use function filesize;
2528
use function implode;
@@ -36,7 +39,7 @@
3639
*/
3740
class Response
3841
{
39-
/*** @var mixed */
42+
/*** @var mixed|Stream */
4043
protected mixed $body;
4144

4245
/*** @var array */
@@ -259,36 +262,34 @@ public function sendContent(): static
259262
if (is_string($this->body)) {
260263
$this->stream->write($this->body);
261264
} elseif ($this->body instanceof Stream) {
262-
promise(function (Closure $resolve, Closure $reject) {
263-
$this->body->onReadable(function (Stream $body) use ($resolve, $reject) {
265+
try {
266+
while (!$this->body->eof()) {
267+
$this->body->waitForReadable();
268+
264269
$content = '';
265-
while ($buffer = $body->read(8192)) {
270+
while ($buffer = $this->body->read(8192)) {
266271
$content .= $buffer;
267272
}
268273

269-
try {
270-
$this->stream->write($content);
271-
} catch (Throwable $exception) {
272-
$body->close();
273-
$reject($exception);
274+
if (!$content) {
275+
throw new RuntimeException('Stream is empty');
274276
}
275277

276-
if ($body->eof()) {
277-
$body->close();
278-
$resolve();
279-
}
280-
});
281-
})->await();
278+
$this->stream->write($content);
279+
}
280+
} finally {
281+
$this->body->close();
282+
}
282283
} elseif ($this->body instanceof Generator) {
283284
foreach ($this->body as $content) {
284285
$this->stream->write($content);
285286
}
286-
if ($this->body->getReturn() === false) {
287-
$this->stream->close();
288-
}
287+
288+
$this->stream->close();
289289
} else {
290290
throw new ConnectionException('The response content is illegal.', ConnectionException::ERROR_ILLEGAL_CONTENT);
291291
}
292+
292293
return $this;
293294
}
294295

0 commit comments

Comments
 (0)