Skip to content

Commit e3db859

Browse files
committed
Disallow cloning Stream objects
Streams hold a reference to the stateful resource handle for their actual contents. Cloning a Stream will not actually clone the underlying resource, thus both streams would still refer to the same resource after cloning and any changes in one stream object would be reflected in the other object. This violates user expectations after a cloning operation. Disallow cloning entirely as the safe default choice. Alternatively a new stream could be created and attached and the contents could be copied over. This can get expensive with larger or infinite streams, though. Signed-off-by: Tim Düsterhus <[email protected]>
1 parent 13f45e5 commit e3db859

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/Stream.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,4 +364,11 @@ private function isValidStreamResourceType(mixed $resource): bool
364364

365365
return false;
366366
}
367+
368+
/**
369+
* Disallow stream cloning.
370+
*/
371+
private function __clone()
372+
{
373+
}
367374
}

test/StreamTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace LaminasTest\Diactoros;
66

77
use CurlHandle;
8+
use Error;
89
use GdImage;
910
use InvalidArgumentException;
1011
use Laminas\Diactoros\Stream;
@@ -679,4 +680,18 @@ public function testSizeReportsNullForPhpInputStreams(): void
679680
$stream = new Stream($resource);
680681
$this->assertNull($stream->getSize());
681682
}
683+
684+
public function testStreamsAreUnclonable(): void
685+
{
686+
$stream = new Stream(fopen('php://temp', 'r+'));
687+
$stream->write('foo');
688+
689+
$this->assertSame('foo', $stream->__toString());
690+
691+
$this->expectException(Error::class);
692+
$this->expectExceptionMessage('private Laminas\Diactoros\Stream::__clone()');
693+
694+
/** @psalm-suppress InvalidClone */
695+
clone $stream;
696+
}
682697
}

0 commit comments

Comments
 (0)