Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## 3.1.1 under development

- no changes in this release.
- New #85: Add `StringStream` (@vjik)

## 3.1.0 December 01, 2025

Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"psr/clock": "^1.0",
"psr/container": "^1.0 || ^2.0",
"psr/event-dispatcher": "^1.0",
"psr/http-message": "^1.1 || ^2.0",
"psr/log": "^2.0|^3.0",
"psr/simple-cache": "^2.0|^3.0"
},
Expand Down
66 changes: 66 additions & 0 deletions docs/guide/en/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,69 @@ sleep(10);

echo $clock->now(); // Same value as above.
```

## String stream [PSR-7](https://www.php-fig.org/psr/psr-7/)

The `StringStream` class is a test-specific implementation of `StreamInterface`.
It allows you to create stream instances with configurable behavior for testing HTTP message handling.

```php
use Yiisoft\Test\Support\HttpMessage\StringStream;

// Create a stream with content
$stream = new StringStream('Hello, World!');

echo $stream; // Hello, World!
echo $stream->getSize(); // 13
echo $stream->read(5); // Hello
echo $stream->getContents(); // , World!
```

You can configure stream behavior through constructor parameters:

```php
// Create a read-only stream
$readOnlyStream = new StringStream('content', writable: false);

// Create a non-seekable stream
$nonSeekableStream = new StringStream('content', seekable: false);

// Create a stream with custom initial position
$stream = new StringStream('Hello', position: 3);
echo $stream->getContents(); // lo
```

Custom metadata can be provided as an array or a closure:

```php
// Array metadata
$stream = new StringStream(
'content',
metadata: [
'uri' => 'php://memory',
'mode' => 'r+',
],
);

// Closure metadata (receives the stream instance)
$stream = new StringStream(
'content',
metadata: static fn(StringStream $s) => [
'size' => $s->getSize(),
'eof' => $s->eof(),
],
);
```

The stream provides helper methods to check its state:

```php
$stream = new StringStream('content');

$stream->isClosed(); // false
$stream->isDetached(); // false
$stream->getPosition(); // 0

$stream->close();
$stream->isClosed(); // true
```
236 changes: 236 additions & 0 deletions src/HttpMessage/StringStream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Test\Support\HttpMessage;

use Closure;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
use LogicException;

use function is_array;
use function strlen;

/**
* A test-specific implementation of PSR-7 stream.
*
* Allows creating stream instances with configurable behavior for testing HTTP message handling.
*
* @psalm-type MetadataClosure = Closure(StringStream): array<string, mixed>
*/
final class StringStream implements StreamInterface
{
private bool $closed = false;
private bool $detached = false;

/**
* @param string $content Initial stream content.
* @param int $position Initial position of the stream pointer.
* @param bool $readable Whether the stream is readable.
* @param bool $writable Whether the stream is writable.
* @param bool $seekable Whether the stream is seekable.
* @param array|Closure|null $metadata Custom metadata as an array or a closure that receives
* the stream instance and returns an array.
*
* @psalm-param MetadataClosure|array|null $metadata
*/
public function __construct(
private string $content = '',
private int $position = 0,
private bool $readable = true,
private bool $writable = true,
private bool $seekable = true,
private Closure|array|null $metadata = null,
) {
$size = strlen($this->content);
if ($this->position < 0 || $this->position > $size) {
throw new LogicException(
sprintf('Position %d is out of valid range [0, %d].', $this->position, $size)
);
}
}

public function __toString(): string
{
return $this->content;
}

/**
* Checks whether the stream has been closed.
*/
public function isClosed(): bool
{
return $this->closed;
}

/**
* Checks whether the stream has been detached.
*/
public function isDetached(): bool
{
return $this->detached;
}

/**
* Returns the current position of the stream pointer.
*/
public function getPosition(): int
{
return $this->position;
}

public function close(): void
{
$this->closed = true;
}

public function detach()
{
$this->detached = true;
$this->close();
return null;
}

public function getSize(): ?int
{
return $this->getContentSize();
}

public function tell(): int
{
if ($this->closed) {
throw new RuntimeException('Stream is closed.');
}

return $this->position;
}

public function eof(): bool
{
return $this->closed || $this->position >= $this->getContentSize();
}

public function isSeekable(): bool
{
return $this->seekable && !$this->closed;
}

public function seek(int $offset, int $whence = SEEK_SET): void
{
if (!$this->seekable) {
throw new RuntimeException('Stream is not seekable.');
}

if ($this->closed) {
throw new RuntimeException('Stream is closed.');
}

$size = $this->getContentSize();

$newPosition = match ($whence) {
SEEK_SET => $offset,
SEEK_CUR => $this->position + $offset,
SEEK_END => $size + $offset,
default => throw new RuntimeException('Invalid whence value.'),
};

if ($newPosition < 0 || $newPosition > $size) {
throw new RuntimeException('Invalid seek position.');
}

$this->position = $newPosition;
}

public function rewind(): void
{
$this->seek(0);
}

public function isWritable(): bool
{
return $this->writable && !$this->closed;
}

public function write(string $string): int
{
if (!$this->writable) {
throw new RuntimeException('Stream is not writable.');
}

if ($this->closed) {
throw new RuntimeException('Stream is closed.');
}

$size = strlen($string);
$this->content = substr($this->content, 0, $this->position)
. $string
. substr($this->content, $this->position + $size);
$this->position = min($this->position + $size, $this->getContentSize());

return $size;
}

public function isReadable(): bool
{
return $this->readable && !$this->closed;
}

public function read(int $length): string
{
if (!$this->readable) {
throw new RuntimeException('Stream is not readable.');
}

if ($this->closed) {
throw new RuntimeException('Stream is closed.');
}

if ($length < 0) {
throw new RuntimeException('Length cannot be negative.');
}

if ($this->position >= $this->getContentSize()) {

Check warning on line 193 in src/HttpMessage/StringStream.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.5-ubuntu-latest

Escaped Mutant for Mutator "GreaterThanOrEqualTo": @@ @@ if ($length < 0) { throw new RuntimeException('Length cannot be negative.'); } - if ($this->position >= $this->getContentSize()) { + if ($this->position > $this->getContentSize()) { return ''; } $result = substr($this->content, $this->position, $length);
return '';

Check warning on line 194 in src/HttpMessage/StringStream.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.5-ubuntu-latest

Escaped Mutant for Mutator "ReturnRemoval": @@ @@ throw new RuntimeException('Length cannot be negative.'); } if ($this->position >= $this->getContentSize()) { - return ''; + } $result = substr($this->content, $this->position, $length); $this->position += strlen($result);
}

$result = substr($this->content, $this->position, $length);
$this->position += strlen($result);

return $result;
}

public function getContents(): string
{
return $this->read(
$this->getContentSize() - $this->position,

Check warning on line 206 in src/HttpMessage/StringStream.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.5-ubuntu-latest

Escaped Mutant for Mutator "Minus": @@ @@ } public function getContents(): string { - return $this->read($this->getContentSize() - $this->position); + return $this->read($this->getContentSize() + $this->position); } public function getMetadata(?string $key = null) {
);
}

public function getMetadata(?string $key = null)
{
if ($this->closed) {
return $key === null ? [] : null;
}

$metadata = match (true) {
is_array($this->metadata) => $this->metadata,
$this->metadata instanceof Closure => ($this->metadata)($this),
default => [
'eof' => $this->eof(),
'seekable' => $this->isSeekable(),
],
};

if ($key === null) {
return $metadata;
}

return $metadata[$key] ?? null;
}

private function getContentSize(): int
{
return strlen($this->content);
}
}
Loading
Loading