Skip to content

Commit

Permalink
Return closed stream if STDIO stream is closed (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski authored Sep 1, 2023
1 parent eba7c80 commit 408a3b4
Show file tree
Hide file tree
Showing 3 changed files with 43 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
38 changes: 38 additions & 0 deletions src/Internal/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?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
{
if (\is_resource($resource) && \get_resource_type($resource) === 'stream') {
return new ReadableResourceStream($resource);
}

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

return $stream;
}

/**
* @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 408a3b4

Please sign in to comment.