Skip to content

Commit

Permalink
Return closed stream if STDIO stream is closed
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Sep 1, 2023
1 parent 7e7a775 commit 8fc6edb
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
"Amp\\ByteStream\\": "src"
},
"files": [
"src/functions.php"
"src/functions.php",
"src/Internal/functions.php"
]
},
"autoload-dev": {
Expand Down
33 changes: 33 additions & 0 deletions src/Internal/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php declare(strict_types=1);

namespace Amp\ByteStream\Internal;

use Amp\ByteStream\ReadableResourceStream;
use Amp\ByteStream\WritableResourceStream;

/**
* @internal
* @param resource $resource Stream resource.
*/
function tryToCreateReadableStreamFromResource($resource): ReadableResourceStream
{
return \is_resource($resource) && \get_resource_type($resource) === 'stream'
? new ReadableResourceStream($resource)
: new ReadableResourceStream(\fopen('php://memory', 'rb'));
}

/**
* @internal
* @param resource $resource Stream resource.
*/
function tryToCreateWritableStreamFromResource($resource): WritableResourceStream
{
if (\is_resource($resource) && \get_resource_type($resource) === 'stream') {
return new WritableResourceStream($resource);
}

$stream = new WritableResourceStream(\fopen('php://memory', 'wb'));
$stream->close();

return $stream;
}
6 changes: 3 additions & 3 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ function getStdin(): ReadableResourceStream

$map ??= new \WeakMap();

return $map[EventLoop::getDriver()] ??= new ReadableResourceStream(\STDIN);
return $map[EventLoop::getDriver()] ??= Internal\tryToCreateReadableStreamFromResource(\STDIN);
}

/**
Expand All @@ -104,7 +104,7 @@ function getStdout(): WritableResourceStream

$map ??= new \WeakMap();

return $map[EventLoop::getDriver()] ??= new WritableResourceStream(\STDOUT);
return $map[EventLoop::getDriver()] ??= Internal\tryToCreateWritableStreamFromResource(\STDOUT);
}

/**
Expand All @@ -116,7 +116,7 @@ function getStderr(): WritableResourceStream

$map ??= new \WeakMap();

return $map[EventLoop::getDriver()] ??= new WritableResourceStream(\STDERR);
return $map[EventLoop::getDriver()] ??= Internal\tryToCreateWritableStreamFromResource(\STDERR);
}

/**
Expand Down

0 comments on commit 8fc6edb

Please sign in to comment.