diff --git a/.github/workflows/Codecov.yml b/.github/workflows/Codecov.yml
index 4a871bb..a83f5c0 100644
--- a/.github/workflows/Codecov.yml
+++ b/.github/workflows/Codecov.yml
@@ -13,8 +13,6 @@ jobs:
build:
uses: The-FireHub-Project/.github/.github/workflows/Codecov.yml@master
with:
- phpVersion: '8.5'
- phpExtensions: ${{ vars.PHP_EXTENSIONS }}
tools: "phpunit:13.x"
suites: '["unit"]'
secrets:
diff --git a/.github/workflows/PHPStan.yml b/.github/workflows/PHPStan.yml
index 62e061a..c553334 100644
--- a/.github/workflows/PHPStan.yml
+++ b/.github/workflows/PHPStan.yml
@@ -10,8 +10,6 @@ jobs:
uses: The-FireHub-Project/.github/.github/workflows/RunCommandOnMatrix.yml@master
with:
title: "Run PHPStan"
- phpVersions: ${{ vars.PHP_VERSIONS }}
- phpExtensions: ${{ vars.PHP_EXTENSIONS }}
tools: "phpstan:2.x"
command: "phpstan analyse"
secrets:
diff --git a/.github/workflows/PHPUnit.yml b/.github/workflows/PHPUnit.yml
index 3d8ae28..556cccb 100644
--- a/.github/workflows/PHPUnit.yml
+++ b/.github/workflows/PHPUnit.yml
@@ -10,8 +10,6 @@ jobs:
uses: The-FireHub-Project/.github/.github/workflows/RunCommandOnMatrix.yml@master
with:
title: "Run PHPUnit"
- phpVersions: ${{ vars.PHP_VERSIONS }}
- phpExtensions: ${{ vars.PHP_EXTENSIONS }}
tools: "phpunit:13.x"
command: "phpunit"
secrets:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 510590d..80941ea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,12 +5,17 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-## [[v0.2.1](https://github.com/The-FireHub-Project/Foundation/compare/v0.2.1...v0.2.0)] – 2026-11-03
+# [[v0.3.0](https://github.com/The-FireHub-Project/Foundation/compare/v0.2.1...v0.3.0)] – 2026-11-06
+
+### Added
+* Introduce Streams by @dieselxxx
+
+## [[v0.2.1](https://github.com/The-FireHub-Project/Foundation/compare/v0.2.0...v0.2.1)] – 2026-11-03
### Added
* Introduce `Origin`, `InvalidOriginException`, and default port resolution for URI schemes by @dieselxxx
-## [[v0.2.0](https://github.com/The-FireHub-Project/Foundation/compare/v0.2.0...v0.1.0)] – 2026-11-02
+## [[v0.2.0](https://github.com/The-FireHub-Project/Foundation/compare/v0.1.0...v0.2.0)] – 2026-11-02
### Added
* Create URI by @dieselxxx
diff --git a/README.md b/README.md
index 5fb2b9f..98ce6ae 100644
--- a/README.md
+++ b/README.md
@@ -12,84 +12,124 @@
/>
-[](https://github.com/The-FireHub-Project/Foundation/actions/workflows/PHPStan.yml)
-[](https://github.com/The-FireHub-Project/Foundation/actions/workflows/PHPUnit.yml)
-[](https://app.codecov.io/gh/The-FireHub-Project/Foundation/tree/develop)
-
-
+
+
+
-
+
-
+
+
+
+
+
+
+
+
+
+ * use FireHub\Foundation\Char;
+ *
+ * $char = new Char('F')->bytes();
+ *
+ * // 1
+ *
+ * $char = new Char('🔥')->bytes();
+ *
+ * // 4
+ *
+ *
+ * @since 1.0.0
+ *
+ * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the byte length.
+ *
+ * @return positive-int The number of bytes.
+ */
+ public function bytes ():int {
+
+ /** @var positive-int */
+ return Runtime\Str\SB\Inspection::length($this->value);
+
+ }
+
}
\ No newline at end of file
diff --git a/src/Char/Byte.php b/src/Char/Byte.php
new file mode 100644
index 0000000..1a19d22
--- /dev/null
+++ b/src/Char/Byte.php
@@ -0,0 +1,116 @@
+
+ * @copyright 2026-present The FireHub Project - All rights reserved
+ * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0
+ *
+ * @php-version >=8.5
+ * @package Foundation
+ */
+
+namespace FireHub\Foundation\Char;
+
+use FireHub\Core\Type\Char;
+use FireHub\Core\Type\Char\Ordinal;
+use FireHub\Foundation\Char\Exception\InvalidLengthException;
+use FireHub\Runtime;
+
+/**
+ * ### Provides an immutable byte value object
+ *
+ * Represents exactly one raw byte without character-encoding semantics.
+ * @since 1.0.0
+ *
+ * @template TValue of non-empty-string
+ *
+ * @extends \FireHub\Core\Type\Char+ * The raw byte value. + *
+ * + * @throws \FireHub\Foundation\Char\Exception\InvalidLengthException If the value does not contain exactly one byte. + * @throws \FireHub\Core\Exception\FireHubException If the condition is not met. + * @throws \FireHub\Core\Type\Exception\ValueObjectException If the exception is not a FireHubException. + * + * @return void + */ + public function __construct ( + private string $value + ) { + + $this->guard( + fn() => Runtime\Str\SB\Inspection::length($this->value) === 1, + fn() => new InvalidLengthException + ); + + } + + /** + * ### Creates a new Byte instance from ordinal value + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Char\SB::chr() To get the character value. + * + * @param \FireHub\Core\Type\Char\Ordinal+ * The ordinal value. + *
+ * + * @throws \FireHub\Foundation\Char\Exception\InvalidLengthException If the value does not contain exactly one byte. + * @throws \FireHub\Core\Exception\FireHubException If the condition is not met. + * @throws \FireHub\Core\Type\Exception\ValueObjectException If the exception is not a FireHubException. + * + * @return static+ * Hashing algorithm. + *
+ * + * @return void + */ + public function __construct ( + private readonly Algorithm $algorithm = Algorithm::SHA256 + ) { + + $this->context = Runtime\Hash::initialize($algorithm); + + } + + /** + * ### Updates the hash with additional bytes + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Hash::update() To update the hashing context. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the string. + * + * @param string $data+ * Bytes to include in the hash. + *
+ * + * @return void + */ + public function update (string $data):void { + + if ($data === '') return; + + Runtime\Hash::update( + $this->context, + $data + ); + + $this->bytes += Runtime\Str\SB\Inspection::length($data); + + } + + /** + * ### Gets the current hash digest + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Hash::digest() To get the hash digest. + * + * @param bool $binary [optional]+ * Whether to return the raw binary digest. + *
+ * + * @return non-empty-string Hash digest. + */ + public function digest (bool $binary = false):string { + + return Runtime\Hash::digest( + $this->context, + $binary + ); + + } + + /** + * ### Gets the number of hashed bytes + * @since 1.0.0 + * + * @return non-negative-int Number of hashed bytes. + */ + public function bytes ():int { + + return $this->bytes; + + } + + /** + * ### Gets the hashing algorithm + * @since 1.0.0 + * + * @return \FireHub\Runtime\Hash\Algorithm Hashing algorithm. + */ + public function algorithm ():Algorithm { + + return $this->algorithm; + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Buffer/DuplexMode.php b/src/IO/Stream/Buffer/DuplexMode.php new file mode 100644 index 0000000..176d8d8 --- /dev/null +++ b/src/IO/Stream/Buffer/DuplexMode.php @@ -0,0 +1,46 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Buffer; + +/** + * ### Buffered Duplex Mode + * + * Defines how a buffered stream coordinates transitions between reading and writing. + * @since 1.0.0 + */ +enum DuplexMode { + + /** + * ### Shared Position + * + * Reading and writing share the same logical position. + * + * Switching from reading to writing may require seeking backward to compensate for unread prefetched bytes. + * @since 1.0.0 + */ + case SHARED_POSITION; + + /** + * ### Independent Directions + * + * Reading and writing operate independently. + * + * Unread prefetched data is preserved when switching to writing. + * + * Intended for full-duplex transports such as TCP connections. + * @since 1.0.0 + */ + case INDEPENDENT_DIRECTIONS; + +} \ No newline at end of file diff --git a/src/IO/Stream/Buffer/Reader.php b/src/IO/Stream/Buffer/Reader.php new file mode 100644 index 0000000..b03c696 --- /dev/null +++ b/src/IO/Stream/Buffer/Reader.php @@ -0,0 +1,349 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Buffer; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Buffered Reader + * + * Provides buffered reading for an existing readable stream. + * + * Reduces the number of underlying read operations by reading larger blocks into an internal buffer. + * + * The underlying stream remains owned by its original owner. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + */ +final class Reader implements Readable { + + /** + * ### Internal read buffer + * @since 1.0.0 + */ + private string $buffer = ''; + + /** + * ### Current position within the buffer + * @since 1.0.0 + */ + private int $position = 0; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $stream+ * Underlying readable stream. + *
+ * @param positive-int $buffer_size [optional]+ * Maximum number of bytes to prefetch. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffer size is invalid. + * + * @return void + */ + public function __construct ( + private readonly Readable $stream, + private readonly int $buffer_size = 8192 + ) { + + if ($buffer_size <= 0) + throw new StreamException( + 'Buffer size must be greater than zero.' + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::isClosed() To check if the underlying stream is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::isReadable() To check if the underlying stream is readable. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::isClosed() To check if the buffered reader is closed. + */ + public function isReadable ():bool { + + return !$this->isClosed() && $this->stream->isReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::size() To get the size of the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::unreadBytes() To get the number of unread buffered bytes. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::fill() To fill the internal buffer. + * @uses \FireHub\Runtime\Str\SB\Access::part() To extract data from the buffer. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the buffer length. + * @uses \FireHub\Runtime\Math::min() To calculate the number of bytes to return. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed, or the read + * length is invalid. + */ + public function read (int $length):string { + + $this->requireOpen(); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0) return ''; + + if ($this->unreadBytes() === 0) { + + if ($this->stream->eof()) return ''; + + $this->fill(); + + } + + $available = $this->unreadBytes(); + + if ($available === 0) return ''; + + $take = Runtime\Math::min( + $length, + $available + ); + + $result = Runtime\Str\SB\Access::part( + $this->buffer, + $this->position, + $take + ); + + $this->position += $take; + + if ($this->position === Runtime\Str\SB\Inspection::length($this->buffer)) { + + $this->buffer = ''; + $this->position = 0; + + } + + return $result; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::read() To read from the underlying stream. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::size() To get the size of the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed, or the stream + * returns no data before reaching EOF. + */ + public function contents ():string { + + $this->requireOpen(); + + $contents = ''; + + while (!$this->eof()) { + + $chunk = $this->read($this->buffer_size); + + if ($chunk === '') { + + if ($this->eof()) break; // @phpstan-ignore if.alwaysFalse + + throw new StreamException( + 'The stream returned no data before reaching EOF.' + ); + + } + + $contents .= $chunk; + + } + + return $contents; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::unreadBytes() To get the number of unread buffered bytes. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::eof() To check if the underlying stream is at EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed. + */ + public function eof ():bool { + + $this->requireOpen(); + + return $this->unreadBytes() === 0 + && $this->stream->eof(); + + } + + /** + * ### Gets the number of unread buffered bytes + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the internal buffer. + * + * @return non-negative-int Number of unread bytes. + */ + public function unreadBytes ():int { + + /** @var non-negative-int */ + return Runtime\Str\SB\Inspection::length($this->buffer) - $this->position; + + } + + /** + * ### Discards unread buffered data + * + * Does not change the underlying stream position. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::requireOpen() To check if the buffered reader is open. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed. + */ + public function clear ():void { + + $this->requireOpen(); + + $this->buffer = ''; + $this->position = 0; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + if ($this->closed) return; + + $this->buffer = ''; + $this->position = 0; + $this->closed = true; + + } + + /** + * ### Fills the internal buffer + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::read() To read from the underlying stream. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::eof() To check if the underlying stream is at EOF. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the buffer. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream cannot make progress. + */ + private function fill ():void { + + $chunk = $this->stream->read($this->buffer_size); + + if ($chunk === '') { + + if (!$this->stream->eof()) + throw new StreamException( + 'The stream returned no data before reaching EOF.' + ); + + return; + + } + + if (Runtime\Str\SB\Inspection::length($chunk) > $this->buffer_size) + throw new StreamException( + 'The stream returned more bytes than requested.' + ); + + $this->buffer = $chunk; + $this->position = 0; + + } + + /** + * ### Requires an open stream + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\BufferedReader::isClosed() To check if the buffered reader is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The buffered reader is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Buffer/Stream.php b/src/IO/Stream/Buffer/Stream.php new file mode 100644 index 0000000..0bd26fa --- /dev/null +++ b/src/IO/Stream/Buffer/Stream.php @@ -0,0 +1,448 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Buffer; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Writable, Seekable +}; +use FireHub\Core\Type\IO\SeekOrigin; +use FireHub\Foundation\IO\Stream\Exception\StreamException; + +/** + * ### Buffered Stream + * + * Combines buffered reading and writing for a duplex stream. + * + * Coordinates transitions between reading and writing to preserve the logical stream position. + * + * Switching from reading to writing requires seeking when unread prefetched bytes remain. + * + * The underlying stream is not automatically closed. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + * + * @phpstan-type IncomingStream = (\FireHub\Core\Boundary\IO\Stream\Readable&\FireHub\Core\Boundary\IO\Stream\Writable) + */ +final class Stream implements Readable, Writable { + + /** + * ### Buffered reader + * @since 1.0.0 + */ + private readonly Reader $reader; + + /** + * ### Buffered writer + * @since 1.0.0 + */ + private readonly Writer $writer; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Last operation was reading + * @since 1.0.0 + */ + private bool $reading = false; + + /** + * ### Last operation was writing + * @since 1.0.0 + */ + private bool $writing = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param IncomingStream $stream+ * Underlying readable and writable stream. + *
+ * @param positive-int $read_buffer_size [optional]+ * Read buffer capacity. + *
+ * @param positive-int $write_buffer_size [optional]+ * Write buffer capacity. + *
+ * @param \FireHub\Foundation\IO\Stream\Buffer\DuplexMode $mode [optional]+ * Defines how reading and writing are coordinated. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffer size is invalid. + * + * @return void + */ + public function __construct ( + private readonly Readable&Writable $stream, + int $read_buffer_size = 8192, + int $write_buffer_size = 8192, + private readonly DuplexMode $mode = DuplexMode::SHARED_POSITION + ) { + + $this->reader = new Reader( + $stream, + $read_buffer_size + ); + + $this->writer = new Writer( + $stream, + $write_buffer_size + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses IncomingStream::isClosed() To check if the buffered reader is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses IncomingStream::isClosed() To check if the buffered reader is closed. + * @uses IncomingStream::isReadable() To check if the underlying stream is readable. + */ + public function isReadable ():bool { + + return !$this->isClosed() && $this->stream->isReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses IncomingStream::isClosed() To check if the buffered reader is closed. + * @uses IncomingStream::isWritable() To check if the underlying stream is writable. + */ + public function isWritable ():bool { + + return !$this->isClosed() && $this->stream->isWritable(); + + } + + /** + * @inheritDoc + * + * @uses IncomingStream::size() To get the size of the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::prepareRead() To prepare the stream for reading. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::read() To read from the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed, or the stream + * returns no data before reaching EOF. + */ + public function read (int $length):string { + + $this->requireOpen(); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0) return ''; + + $this->prepareRead(); + + return $this->reader->read($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::prepareRead() To prepare the stream for reading. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::contents() To read the entire contents of the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed. + */ + public function contents ():string { + + $this->requireOpen(); + + $this->prepareRead(); + + return $this->reader->contents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::requireOpen() To check whether the stream is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::prepareRead() To prepare the stream for reading. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::eof() To check whether EOF has been reached. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed or flushing fails. + */ + public function eof ():bool { + + $this->requireOpen(); + + if ( + $this->writing + && $this->mode === DuplexMode::SHARED_POSITION + ) $this->prepareRead(); + + return $this->reader->eof(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::prepareWrite() To prepare the stream for writing. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::write() To write to the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered writer is closed or the underlying + * stream cannot make progress. + */ + public function write (string $data):int { + + $this->requireOpen(); + + if ($data === '') return 0; + + $this->prepareWrite(); + + return $this->writer->write($data); + + } + + /** + * ### Flushes pending writes + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::requireOpen() To check if the buffered writer is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::flush() To flush the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered writer is closed. + */ + public function flush ():void { + + $this->requireOpen(); + + $this->writer->flush(); + + } + + /** + * ### Gets pending write bytes + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::pendingBytes() To get the number of pending bytes. + * + * @return non-negative-int Pending bytes. + */ + public function pendingBytes ():int { + + return $this->writer->pendingBytes(); + + } + + /** + * ### Gets unread buffered bytes + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::unreadBytes() To get the number of unread bytes. + * + * @return non-negative-int Unread bytes. + */ + public function unreadBytes ():int { + + return $this->reader->unreadBytes(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::close() To close the underlying writer. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::close() To close the underlying reader. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream cannot be closed. + * + * @return void + */ + public function close ():void { + + if ($this->closed) return; + + $this->writer->close(); + + $this->reader->close(); + + $this->closed = true; + + } + + /** + * ### Prepares the stream for reading + * + * Flushes pending writes before reading when the stream uses a shared logical position. + * + * Independent-direction streams preserve pending writes. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::flush() To flush pending writes. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If flushing fails. + * + * @return void + */ + private function prepareRead ():void { + + if ( + $this->writing + && $this->mode === DuplexMode::SHARED_POSITION + ) $this->writer->flush(); + + $this->writing = false; + $this->reading = true; + + } + + /** + * ### Prepares the stream for writing + * + * Restores the logical position when unread prefetched bytes remain. + * + * Non-seekable streams cannot safely switch from buffered reading to writing while unread data remains. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::restoreReadPosition() To restore the logical position. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered reader is closed or the stream + * cannot be seeked. + * + * @return void + */ + private function prepareWrite ():void { + + if ($this->reading) { + + if ($this->mode === DuplexMode::SHARED_POSITION) + $this->restoreReadPosition(); + + $this->reading = false; + + } + + $this->writing = true; + + } + + /** + * ### Restores the logical read position + * + * Repositions a shared-position stream to account for unread prefetched + * bytes before switching to writing. + * + * Buffered data is discarded only after successful repositioning. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::unreadBytes() To get the number of unread bytes. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Reader::clear() To discard buffered data. + * @uses \FireHub\Core\Boundary\IO\Stream\Seekable::isSeekable() To check seeking support. + * @uses \FireHub\Core\Boundary\IO\Stream\Seekable::seek() To restore the logical position. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking is required but unavailable. + * + * @return void + */ + private function restoreReadPosition ():void { + + $unread = $this->reader->unreadBytes(); + + if ($unread > 0) { + + if ( + !$this->stream instanceof Seekable + || !$this->stream->isSeekable() + ) throw new StreamException( + 'Cannot restore the logical position of a non-seekable stream.' + ); + + $this->stream->seek( + -$unread, + SeekOrigin::CURRENT + ); + + } + + $this->reader->clear(); + + } + + /** + * ### Requires an open stream + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Stream::isClosed() To check if the buffered stream is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered stream is closed. + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The buffered stream is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Buffer/Writer.php b/src/IO/Stream/Buffer/Writer.php new file mode 100644 index 0000000..15f93fd --- /dev/null +++ b/src/IO/Stream/Buffer/Writer.php @@ -0,0 +1,320 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Buffer; + +use FireHub\Core\Boundary\IO\Stream\Writable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Buffered Writer + * + * Provides buffered writing for an existing writable stream. + * + * Accumulates small writes in memory and forwards them to the underlying stream when the buffer reaches its + * configured capacity. + * + * Pending data can be explicitly forwarded using flush(). + * + * The underlying stream remains owned by its original owner. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + */ +final class Writer implements Writable { + + /** + * ### Pending write buffer + * @since 1.0.0 + */ + private string $buffer = ''; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Writable $stream+ * Underlying writable stream. + *
+ * @param positive-int $buffer_size [optional]+ * Maximum buffered bytes before automatic flushing. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffer size is invalid. + * + * @return void + */ + public function __construct ( + private readonly Writable $stream, + private readonly int $buffer_size = 8192 + ) { + + if ($buffer_size <= 0) + throw new StreamException( + 'Buffer size must be greater than zero.' + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::isClosed() To check if the underlying stream is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::isWritable() To check if the underlying stream is writable. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::isClosed() To check if the buffered reader is closed. + */ + public function isWritable ():bool { + + return !$this->isClosed() && $this->stream->isWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::size() To get the underlying stream size. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered writer is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::flush() To flush pending buffered data. + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::writeDirect() To write data directly to the underlying stream. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::isWritable() To check if the underlying stream is writable. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the string. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered writer is closed or the + * underlying stream is not writable. + */ + public function write (string $data):int { + + $this->requireOpen(); + + if (!$this->stream->isWritable()) + throw new StreamException( + 'The underlying stream is not writable.' + ); + + $length = Runtime\Str\SB\Inspection::length($data); + + if ($length === 0) return 0; + + $pending = Runtime\Str\SB\Inspection::length($this->buffer); + + if ($pending + $length < $this->buffer_size) { + + $this->buffer .= $data; + + return $length; + + } + + if ($pending > 0) $this->flush(); + + if ($length >= $this->buffer_size) { + + $this->writeDirect($data); + + return $length; + + } + + $this->buffer = $data; + + return $length; + + } + + /** + * ### Flushes pending buffered data + * + * Writes all pending bytes to the underlying stream. + * + * Handles partial writes by continuing until all bytes are forwarded. + * + * If writing fails, bytes that have not been successfully written remain in the buffer. + * + * This method does not guarantee physical disk synchronization. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::requireOpen() To check if the buffered reader is open. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::write() To write data to the underlying stream. + * @uses \FireHub\Runtime\Str\SB\Access::part() To get a part of the string. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the string. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream cannot make progress. + * + * @return void + */ + public function flush ():void { + + $this->requireOpen(); + + while ($this->buffer !== '') { + + $written = $this->stream->write($this->buffer); + + if ($written <= 0) + throw new StreamException( + 'The underlying stream could not accept buffered data.' + ); + + if ($written > Runtime\Str\SB\Inspection::length($this->buffer)) + throw new StreamException( + 'The underlying stream reported an invalid write length.' + ); + + $this->buffer = Runtime\Str\SB\Access::part( + $this->buffer, + $written + ); + + } + + } + + /** + * ### Gets the number of pending buffered bytes + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the string. + * + * @return non-negative-int Pending bytes. + */ + public function pendingBytes ():int { + + return Runtime\Str\SB\Inspection::length($this->buffer); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::flush() To flush pending buffered data. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream cannot make progress. + */ + public function close ():void { + + if ($this->closed) return; + + $this->flush(); + + $this->closed = true; + + } + + /** + * ### Requires an open stream + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Buffer\Writer::isClosed() To check if the buffered writer is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the buffered writer is closed. + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The buffered writer is closed.' + ); + + } + + /** + * ### Writes data directly to the underlying stream + * + * Continues writing until all bytes have been transferred. + * + * Handles partial writes without discarding unwritten data. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::write() To write data to the underlying stream. + * @uses \FireHub\Runtime\Str\SB\Access::part() To get a part of the string. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the string. + * + * @param string $data+ * Data to write. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream cannot make progress. + * + * @return void + */ + private function writeDirect (string $data):void { + + $length = Runtime\Str\SB\Inspection::length($data); + + $offset = 0; + + while ($offset < $length) { + + $written = $this->stream->write( + Runtime\Str\SB\Access::part($data, $offset) + ); + + if ($written <= 0) + throw new StreamException( + 'The underlying stream could not accept the remaining data.' + ); + + if ($written > $length - $offset) + throw new StreamException( + 'The underlying stream reported an invalid write length.' + ); + + $offset += $written; + + } + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Bzip2.php b/src/IO/Stream/Bzip2.php new file mode 100644 index 0000000..c366f94 --- /dev/null +++ b/src/IO/Stream/Bzip2.php @@ -0,0 +1,185 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Writable +}; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Stream\Enum\OpenMode; +use FireHub\Runtime; + +/** + * ### Bzip2 Stream + * + * Provides a readable and writable stream backed by PHP's compress.bzip2:// stream wrapper. + * + * Allows reading and writing bzip2-compressed files using transparent compression and decompression. + * + * Reading and writing availability depend on the selected opening mode. + * + * Seeking and positioning are not guaranteed by this abstraction. + * + * Requires the PHP bz2 extension. + * @since 1.0.0 + */ +final class Bzip2 extends ResourceStream implements Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the compressed stream. + * @uses \FireHub\Runtime\System\Extension::hasExtension() To validate the extension availability. + * + * @param non-empty-string $path+ * Path to the bzip2-compressed file. + *
+ * @param \FireHub\Runtime\Stream\Enum\OpenMode $mode [optional]+ * Stream opening mode. + * + * Only READ_BINARY and WRITE_BINARY are supported. + * + * Defaults to READ_BINARY. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the extension is unavailable, the opening + * mode is unsupported, or the stream cannot be opened. + * + * @return void + */ + public function __construct (string $path, OpenMode $mode = OpenMode::READ_BINARY) { + + if (!Runtime\System\Extension::hasExtension('bz2')) + throw new StreamException( + 'The bz2 extension is required to open bzip2 streams.' + ); + + if ($path === '') + throw new StreamException( + 'The compressed file path cannot be empty.' + ); + + if ( + $mode !== OpenMode::READ_BINARY + && $mode !== OpenMode::WRITE_BINARY + ) throw new StreamException( + 'Bzip2 streams support only READ_BINARY and WRITE_BINARY opening modes.' + ); + + $resource = Runtime\Stream\Handle::open( + "compress.bzip2://$path", + $mode + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open bzip2 stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Composite/Reader.php b/src/IO/Stream/Composite/Reader.php new file mode 100644 index 0000000..3ddabc9 --- /dev/null +++ b/src/IO/Stream/Composite/Reader.php @@ -0,0 +1,359 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Composite; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Composite Stream Reader + * + * Combines multiple readable streams into a single sequential stream. + * + * Reads data from each source in the order provided, automatically advancing to the next source when the current + * source reaches EOF. + * + * A single read operation may consume bytes from multiple sources. + * + * The underlying streams are borrowed and are not automatically closed. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + */ +final class Reader implements Readable { + + /** + * ### Source streams + * @since 1.0.0 + * + * @var list<\FireHub\Core\Boundary\IO\Stream\Readable> + */ + private readonly array $streams; + + /** + * ### Current source index + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $index = 0; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Access::values() To remove keys from the array. + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable ...$streams+ * Source streams to concatenate in the given order. + *
+ * + * @return void + */ + public function __construct (Readable ...$streams) { + + $this->streams = Runtime\Arr\Access::values($streams); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function isClosed ():bool { + + return $this->closed; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the stream is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isClosed() To check if the stream is closed. + * @uses \FireHub\Runtime\Arr\Inspection::count() To get the number of streams. + */ + public function isReadable ():bool { + + if ($this->closed) return false; + + for ( + $index = $this->index, $index_max = Runtime\Arr\Inspection::count($this->streams); + $index < $index_max; + $index++ + ) { + + $stream = $this->streams[$index]; // @phpstan-ignore offsetAccess.notFound + + if ($stream->isClosed() || !$stream->isReadable()) + return false; + + } + + return true; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Composite\Reader::requireOpen() To ensure the reader is open. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function size ():null { + + $this->requireOpen(); + + return null; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Composite\Reader::requireOpen() To ensure the reader is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if the stream is at EOF. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the stream is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isClosed() To check if the stream is closed. + * @uses \FireHub\Runtime\Arr\Inspection::count() To get the number of streams. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the read data. + * @uses \FireHub\Runtime\Str\SB\Access::part() To extract the read data. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read from the stream. + * @uses \FireHub\Runtime\Math::min() To clamp the read length. + * @uses \FireHub\Runtime\Arr\Inspection::count() To get the number of streams. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To count the received bytes. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the length is negative, the reader is + * closed, or an underlying source violates the read contract. + */ + public function read (int $length):string { + + $this->requireOpen(); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0) return ''; + + $result = ''; + + while ( + Runtime\Str\SB\Inspection::length($result) < $length + && $this->index < count($this->streams) + ) { + + $stream = $this->streams[$this->index]; + + if ($stream->isClosed() || !$stream->isReadable()) + throw new StreamException( + 'The current composite source is not readable.' + ); + + if ($stream->eof()) { + + $this->index++; + + continue; + + } + + /** @var non-negative-int $remaining */ + $remaining = $length - Runtime\Str\SB\Inspection::length($result); + + $chunk = $stream->read($remaining); + + $received = Runtime\Str\SB\Inspection::length($chunk); + + if ($received > $remaining) + throw new StreamException( + 'The underlying stream returned more bytes than requested.' + ); + + if ($chunk === '') { + + if ($stream->eof()) { // @phpstan-ignore if.alwaysFalse + + $this->index++; + + continue; + + } + + throw new StreamException( + 'The underlying stream returned no data before reaching EOF.' + ); + + } + + $result .= $chunk; + + if ($stream->eof()) // @phpstan-ignore if.alwaysFalse + $this->index++; + + } + + return $result; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Composite\Reader::requireOpen() To ensure the reader is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if the stream is at EOF. + * @uses \FireHub\Foundation\IO\Stream\Composite\Reader::read() To read from the stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + $this->requireOpen(); + + $contents = ''; + + while (!$this->eof()) { + + $chunk = $this->read(8192); + + if ($chunk === '') { + + if ($this->eof()) break; // @phpstan-ignore if.alwaysFalse + + throw new StreamException( + 'The composite stream returned no data before reaching EOF.' + ); + + } + + $contents .= $chunk; + + } + + return $contents; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Composite\Reader::requireOpen() To ensure the reader is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if the stream is at EOF. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the stream is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isClosed() To check if the stream is closed. + * @uses \FireHub\Runtime\Arr\Inspection::count() To get the number of streams. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed or an underlying + * source violates the read contract. + */ + public function eof ():bool { + + $this->requireOpen(); + + while ($this->index < Runtime\Arr\Inspection::count($this->streams)) { + + $stream = $this->streams[$this->index]; // @phpstan-ignore offsetAccess.notFound + + if ($stream->isClosed() || !$stream->isReadable()) + throw new StreamException( + 'The current composite source is not readable.' + ); + + if (!$stream->eof()) return false; + + $this->index++; + + } + + return true; + + } + + /** + * ### Gets the current source index + * @since 1.0.0 + * + * @return non-negative-int Current source index. + */ + public function index ():int { + + return $this->index; + + } + + /** + * ### Gets the number of source streams + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Inspection::count() To get the number of streams. + * + * @return non-negative-int Number of source streams. + */ + public function count ():int { + + return Runtime\Arr\Inspection::count($this->streams); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Requires an open reader + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Composite\Reader::isClosed() To check if the reader is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the composite reader is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->closed) + throw new StreamException( + 'The composite reader is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Copier.php b/src/IO/Stream/Copier.php new file mode 100644 index 0000000..2864723 --- /dev/null +++ b/src/IO/Stream/Copier.php @@ -0,0 +1,326 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Writable +}; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Stream Copier + * + * Provides memory-bounded copying between readable and writable streams. + * + * Data is transferred incrementally without materializing the entire source stream in memory. + * + * Partial reads and writes are supported. + * + * Copying starts at the current stream positions. + * + * Streams are not automatically rewound, flushed, or closed. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + */ +final readonly class Copier { + + /** + * ### Copies data between streams + * + * Copies bytes from the source into the destination until EOF is reached or the optional byte limit has been + * satisfied. + * + * Each chunk is completely written before another chunk is read. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Copier::validate() To validate the copy operation. + * @uses \FireHub\Foundation\IO\Stream\Copier::copyChunks() To transfer data between streams. + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $source+ * Source stream. + *
+ * @param \FireHub\Core\Boundary\IO\Stream\Writable $destination+ * Destination stream. + *
+ * @param positive-int $buffer_size [optional]+ * Maximum number of bytes requested per read operation. + * + * Defaults to 65536. + *
+ * @param null|non-negative-int $limit [optional]+ * Maximum number of bytes to copy. + * + * Null copies until EOF. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the copy operation cannot be completed. + * + * @return non-negative-int Number of bytes accepted by the destination. + */ + public static function copy ( + Readable $source, + Writable $destination, + int $buffer_size = 65536, + ?int $limit = null + ):int { + + self::validate( + $source, + $destination, + $buffer_size, + $limit + ); + + if ($limit === 0) return 0; + + return self::copyChunks( + $source, + $destination, + $buffer_size, + $limit + ); + + } + + /** + * ### Validates the copy operation + * + * Ensures that the buffer size, byte limit, source, and destination satisfy the requirements for copying. + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the source is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isWritable() To check if the destination is writable. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isClosed() To check if the source is closed. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isClosed() To check if the destination is closed. + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $source+ * Source stream. + *
+ * @param \FireHub\Core\Boundary\IO\Stream\Writable $destination+ * Destination stream. + *
+ * @param int $buffer_size+ * Requested buffer size. + *
+ * @param null|int $limit+ * Maximum number of bytes to copy. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the copy parameters or streams are invalid. + * + * @return void + */ + private static function validate (Readable $source, Writable $destination, int $buffer_size, ?int $limit):void { + + if ($buffer_size <= 0) + throw new StreamException( + 'Buffer size must be greater than zero.' + ); + + if ($limit !== null && $limit < 0) + throw new StreamException( + 'Copy limit cannot be negative.' + ); + + if ($source->isClosed()) + throw new StreamException( + 'The source stream is closed.' + ); + + if ($destination->isClosed()) + throw new StreamException( + 'The destination stream is closed.' + ); + + if (!$source->isReadable()) + throw new StreamException( + 'The source stream is not readable.' + ); + + if (!$destination->isWritable()) + throw new StreamException( + 'The destination stream is not writable.' + ); + + } + + /** + * ### Copies stream chunks + * + * Coordinates reading and writing until EOF or the byte limit is reached. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Copier::copyChunks() To transfer data between streams. + * @uses \FireHub\Foundation\IO\Stream\Copier::readChunk() To read the next chunk. + * @uses \FireHub\Foundation\IO\Stream\Copier::writeChunk() To write the entire chunk. + * @uses \FireHub\Runtime\Math::min() To clamp the buffer size to the limit. + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $source+ * Source stream. + *
+ * @param \FireHub\Core\Boundary\IO\Stream\Writable $destination+ * Destination stream. + *
+ * @param positive-int $buffer_size+ * Maximum read size. + *
+ * @param null|non-negative-int $limit+ * Maximum number of bytes to copy. + *
+ * + * @uses self::readChunk() To read the next chunk. + * @uses self::writeChunk() To write the entire chunk. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading or writing fails. + * + * @return non-negative-int Number of bytes copied. + */ + private static function copyChunks ( + Readable $source, Writable $destination, int $buffer_size, ?int $limit):int { + + $copied = 0; + + while (true) { + + if ($limit !== null && $copied >= $limit) + break; + + /** @var positive-int $length */ + $length = $limit === null + ? $buffer_size + : Runtime\Math::min($buffer_size, $limit - $copied); + + $chunk = self::readChunk($source, $length); + + if ($chunk === '') break; + + $copied += self::writeChunk( + $destination, + $chunk + ); + + } + + return $copied; + + } + + /** + * ### Reads the next chunk + * + * Reads up to the requested number of bytes. + * + * Returns an empty string only when EOF has been reached. + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if EOF has been reached. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read the next chunk. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To check the length of the returned chunk. + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $source+ * Source stream. + *
+ * @param positive-int $length+ * Maximum number of bytes to read. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the source cannot make progress or returns + * more bytes than requested. + * + * @return string Data read from the source. + */ + private static function readChunk (Readable $source, int $length):string { + + if ($source->eof()) return ''; + + $chunk = $source->read($length); + + if ($chunk === '') { + + if ($source->eof()) return ''; // @phpstan-ignore if.alwaysFalse + + throw new StreamException( + 'The source stream returned no data before reaching EOF.' + ); + + } + + if (Runtime\Str\SB\Inspection::length($chunk) > $length) + throw new StreamException( + 'The source stream returned more bytes than requested.' + ); + + return $chunk; + + } + + /** + * ### Writes an entire chunk + * + * Handles partial writes by repeatedly writing the remaining bytes. + * + * An underlying writing that accepts zero bytes is treated as an error. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Str\SB\Access::part() To get a part of the string. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the string. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::write() To write the entire chunk. + * + * @param \FireHub\Core\Boundary\IO\Stream\Writable $destination+ * Destination stream. + *
+ * @param string $chunk+ * Data to write. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the destination cannot make progress or + * reports an invalid write length. + * + * @return non-negative-int Number of bytes accepted by the destination. + */ + private static function writeChunk (Writable $destination, string $chunk):int { + + $length = Runtime\Str\SB\Inspection::length($chunk); + $offset = 0; + + while ($offset < $length) { + + $remaining = Runtime\Str\SB\Access::part( + $chunk, + $offset + ); + + $written = $destination->write($remaining); + + if ($written <= 0) + throw new StreamException( + 'The destination stream could not accept the remaining data.' + ); + + if ($written > Runtime\Str\SB\Inspection::length($remaining)) + throw new StreamException( + 'The destination stream reported an invalid write length.' + ); + + $offset += $written; + + } + + return $offset; + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Data.php b/src/IO/Stream/Data.php new file mode 100644 index 0000000..8beb9fe --- /dev/null +++ b/src/IO/Stream/Data.php @@ -0,0 +1,195 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Positionable, Readable, Seekable +}; +use FireHub\Core\Type\IO\SeekOrigin; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Data Stream + * + * Provides a readable and seekable stream backed by PHP's data:// stream wrapper. + * + * Allows reading inline data embedded directly within a URI, including plain text and Base64-encoded content. + * + * Unlike filesystem and network streams, this stream retrieves its contents directly from the supplied data URI. + * + * The stream is read-only and supports positioning within the decoded data. + * + * Opening the stream requires PHP's allow_url_fopen configuration directive to be enabled. + * @since 1.0.0 + */ +final class Data extends ResourceStream implements Positionable, Seekable, Readable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the data stream. + * @uses \FireHub\Runtime\Str\SB\Search::startsWith() To validate the URI scheme. + * + * @param non-empty-string $uri+ * Data URI containing inline content. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the URI is invalid or the stream cannot be opened. + * + * @return void + */ + public function __construct (string $uri) { + + if (!Runtime\Str\SB\Search::startsWith('data:', $uri)) + throw new StreamException( + 'Only data stream URIs are supported.' + ); + + $resource = Runtime\Stream\Handle::open( + $uri, + Runtime\Stream\Enum\OpenMode::READ_BINARY + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open data stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsSeekable() To check if the resource is seekable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isSeekable ():bool { + + return $this->resourceIsSeekable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::tellResource() To get the current position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the position cannot be determined. + */ + public function tell ():int { + + return $this->tellResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::seekResource() To seek to a specific position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function seek (int $offset, SeekOrigin $origin = SeekOrigin::START):void { + + $this->seekResource($offset, $origin); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::rewindResource() To rewind the resource to the beginning. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function rewind ():void { + + $this->rewindResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Exception/StreamException.php b/src/IO/Stream/Exception/StreamException.php new file mode 100644 index 0000000..86e5608 --- /dev/null +++ b/src/IO/Stream/Exception/StreamException.php @@ -0,0 +1,33 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Exception; + +use FireHub\Core\Exception\RuntimeException; + +/** + * ### Stream Exception + * + * Represents an error occurring during an input or output stream operation. + * @since 1.0.0 + */ +final class StreamException extends RuntimeException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'An error occurred while processing the stream.'; + +} \ No newline at end of file diff --git a/src/IO/Stream/File.php b/src/IO/Stream/File.php new file mode 100644 index 0000000..1e16d0a --- /dev/null +++ b/src/IO/Stream/File.php @@ -0,0 +1,224 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Positionable, Readable, Seekable, Writable +}; +use FireHub\Core\Type\IO\SeekOrigin; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Stream\Enum\OpenMode; +use FireHub\Runtime; + +/** + * ### File Stream + * + * Provides a readable, writable, and seekable stream backed by PHP's file:// stream wrapper. + * + * Allows reading, writing, and positioning within local filesystem files using a configurable opening mode. + * + * Unlike php://memory and php://temp, this stream operates on persistent filesystem resources. + * + * Reading and writing availability depend on the selected opening mode, while seeking depends on the underlying + * resource capabilities. + * @since 1.0.0 + */ +final class File extends ResourceStream implements Positionable, Seekable, Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the file stream. + * + * @param non-empty-string $path+ * Local filesystem path or file:// URI. + *
+ * @param \FireHub\Runtime\Stream\Enum\OpenMode $mode [optional]+ * File opening mode. + * + * Defaults to READ_BINARY. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the file cannot be opened. + * + * @return void + */ + public function __construct (string $path, OpenMode $mode = OpenMode::READ_BINARY) { + + $resource = Runtime\Stream\Handle::open( + $path, + $mode + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open file stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsSeekable() To check if the resource is seekable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isSeekable ():bool { + + return $this->resourceIsSeekable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::tellResource() To get the current position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the position cannot be determined. + */ + public function tell ():int { + + return $this->tellResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::seekResource() To seek to a specific position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function seek (int $offset, SeekOrigin $origin = SeekOrigin::START):void { + + $this->seekResource($offset, $origin); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::rewindResource() To rewind the resource to the beginning. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function rewind ():void { + + $this->rewindResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource is at the end of the stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/FileDesc.php b/src/IO/Stream/FileDesc.php new file mode 100644 index 0000000..354b922 --- /dev/null +++ b/src/IO/Stream/FileDesc.php @@ -0,0 +1,239 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Positionable, Readable, Seekable, Writable +}; +use FireHub\Core\Type\IO\SeekOrigin; +use FireHub\Core\Foundation\Constant\Environment\Php\PlatformInfo; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Stream\Enum\OpenMode; +use FireHub\Runtime; + +/** + * ### File Descriptor Stream + * + * Provides a readable, writable, and potentially seekable stream backed by PHP's php://fd wrapper. + * + * Allows accessing an existing file descriptor inherited or provided by the current process. + * + * Reading, writing, and positioning capabilities depend on the underlying descriptor and the selected opening mode. + * + * The php://fd wrapper is primarily intended for CLI environments and is not guaranteed to be available in other + * PHP execution environments. + * + * The stream owns the PHP resource opened by this instance. Closing the stream releases that resource and may affect + * the underlying file descriptor. + * @since 1.0.0 + */ +final class FileDesc extends ResourceStream implements Positionable, Seekable, Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the file descriptor stream. + * @uses \FireHub\Core\Foundation\Constant\Environment\Php\PlatformInfo::SAPI To validate the environment. + * + * @param non-negative-int $descriptor+ * Existing file descriptor number. + *
+ * @param \FireHub\Runtime\Stream\Enum\OpenMode $mode [optional]+ * Stream opening mode. + * + * Defaults to READ_BINARY. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the descriptor is invalid or cannot be opened. + * + * @return void + */ + public function __construct (int $descriptor, OpenMode $mode = OpenMode::READ_BINARY) { + + if (PlatformInfo::SAPI !== 'cli') + throw new StreamException( + 'File descriptor streams are supported only in CLI environments.' + ); + + if ($descriptor < 3) + throw new StreamException( + 'Use standard stream classes for descriptors 0, 1, and 2.' + ); + + $resource = Runtime\Stream\Handle::open( + "php://fd/$descriptor", + $mode + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open file descriptor stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsSeekable() To check if the resource is seekable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isSeekable ():bool { + + return $this->resourceIsSeekable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining resource contents. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::tellResource() To get the current stream position. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the position cannot be determined. + */ + public function tell ():int { + + return $this->tellResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::seekResource() To move the stream position. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function seek (int $offset, SeekOrigin $origin = SeekOrigin::START):void { + + $this->seekResource($offset, $origin); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::rewindResource() To rewind the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function rewind ():void { + + $this->rewindResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check whether the stream has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Filter/Attachment.php b/src/IO/Stream/Filter/Attachment.php new file mode 100644 index 0000000..7b0c2b5 --- /dev/null +++ b/src/IO/Stream/Filter/Attachment.php @@ -0,0 +1,139 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Filter; + +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; +use Closure; + +/** + * ### Stream Filter Attachment + * + * Represents a native PHP stream filter attached to an existing stream. + * + * Provides explicit filter removal and tracks whether the attachment remains active. + * + * The attachment does not own the underlying stream. + * + * Closing the parent stream invalidates its filter attachments. + * @since 1.0.0 + * + * @internal + */ +final class Attachment { + + /** + * ### Constructor + * @since 1.0.0 + * + * @param null|resource $resource+ * Native PHP stream filter resource. + *
+ * @param null|Closure $on_removed+ * Callback invoked when the attachment is removed or invalidated. + *
+ * + * @return void + */ + public function __construct ( + private mixed $resource = null, + private ?Closure $on_removed = null + ) {} + + /** + * ### Checks whether the filter is active + * @since 1.0.0 + * + * @uses \FireHub\Runtime\DataIs::resource() To validate the filter resource. + * + * @return bool True if the filter is active. + */ + public function isActive ():bool { + + return Runtime\DataIs::resource($this->resource); + + } + + /** + * ### Removes the filter from its stream + * + * Removes the filter from the native PHP stream filter chain. + * + * Calling this method multiple times has no additional effect. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Attachment::release() To release the attachment. + * @uses \FireHub\Runtime\Stream\Filter::remove() To remove the native stream filter. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If removing the filter fails. + * + * @return void + */ + public function remove ():void { + + if (!$this->isActive()) return; + + /** @var resource $resource */ + $resource = $this->resource; + + if (!Runtime\Stream\Filter::remove($resource)) + throw new StreamException( + 'Unable to remove stream filter.' + ); + + $this->release(); + + } + + /** + * ### Invalidates the filter attachment + * + * Marks the attachment as inactive without attempting to remove the native filter. + * + * Intended for use when the parent stream is closed. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Attachment::release() To release the attachment. + * + * @return void + */ + public function invalidate ():void { + + $this->release(); + + } + + /** + * ### Releases the attachment + * + * Clears the native filter reference and notifies the parent stream. + * @since 1.0.0 + * + * @return void + */ + private function release ():void { + + $this->resource = null; + + $callback = $this->on_removed; + + $this->on_removed = null; + + if ($callback !== null) + $callback(); + + } + + +} \ No newline at end of file diff --git a/src/IO/Stream/Ftp.php b/src/IO/Stream/Ftp.php new file mode 100644 index 0000000..1aafd83 --- /dev/null +++ b/src/IO/Stream/Ftp.php @@ -0,0 +1,183 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Writable +}; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Stream\Enum\OpenMode; +use FireHub\Runtime; + +/** + * ### FTP Stream + * + * Provides a readable or writable stream backed by PHP's ftp:// and ftps:// stream wrappers. + * + * Allows transferring files between the application and remote FTP servers using PHP's native stream functionality. + * + * The stream supports reading or writing depending on the selected opening mode but does not support both operations + * simultaneously. + * + * Unlike local filesystem streams, FTP streams operate over a network connection and do not guarantee seeking or + * positioning capabilities. + * + * Opening the stream may perform network I/O and can fail due to connection errors, authentication failures, server + * restrictions, or timeouts. + * @since 1.0.0 + */ +final class Ftp extends ResourceStream implements Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the FTP stream. + * @uses \FireHub\Runtime\Str\SB\Search::startsWith() To validate the URI scheme. + * + * @param non-empty-string $uri+ * FTP or FTPS URI identifying the remote resource. + *
+ * @param \FireHub\Runtime\Stream\Enum\OpenMode $mode [optional]+ * Stream opening mode. + * + * Only READ_BINARY and WRITE_BINARY are supported. + * + * Defaults to READ_BINARY. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the URI scheme or opening mode is unsupported, + * or the stream cannot be opened. + * + * @return void + */ + public function __construct (string $uri, OpenMode $mode = OpenMode::READ_BINARY) { + + if ( + !Runtime\Str\SB\Search::startsWith('ftp://', $uri) + && !Runtime\Str\SB\Search::startsWith('ftps://', $uri) + ) throw new StreamException( + 'Only FTP and FTPS stream URIs are supported.' + ); + + if ($mode !== OpenMode::READ_BINARY && $mode !== OpenMode::WRITE_BINARY) + throw new StreamException( + 'FTP streams support only READ_BINARY and WRITE_BINARY opening modes.' + ); + + $resource = Runtime\Stream\Handle::open( + $uri, + $mode + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open FTP stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Hash/Reader.php b/src/IO/Stream/Hash/Reader.php new file mode 100644 index 0000000..3156fd8 --- /dev/null +++ b/src/IO/Stream/Hash/Reader.php @@ -0,0 +1,267 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Hash; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\Hash\Context; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Hash\Algorithm; +use FireHub\Runtime; + +/** + * ### Hashing Stream Reader + * + * Calculates an incremental hash of bytes successfully read from an underlying stream. + * + * Only bytes returned to the caller are included in the digest. + * + * The underlying stream is borrowed and is not automatically closed. + * @since 1.0.0 + */ +final class Reader implements Readable { + + /** + * ### Hash context + * @since 1.0.0 + */ + private readonly Context $context; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $stream+ * Underlying readable stream. + *
+ * + * @param \FireHub\Runtime\Hash\Algorithm $algorithm [optional]+ * Hashing algorithm. + *
+ * + * @return void + */ + public function __construct ( + private readonly Readable $stream, + Algorithm $algorithm = Algorithm::SHA256 + ) { + + $this->context = new Context($algorithm); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::isClosed() To check if the reader is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::isClosed() To check if the reader is closed. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the underlying stream is readable. + */ + public function isReadable ():bool { + + return !$this->isClosed() && $this->stream->isReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::requireOpen() To check if the reader is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::size() To get the size of the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::requireOpen() To check if the reader is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read from the underlying stream. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if the underlying stream is at EOF. + * @uses \FireHub\Foundation\Hash\Context::update() To update the hash context. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the read data. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream returns more bytes than + * requested, or returns no data before reaching EOF. + */ + public function read (int $length):string { + + $this->requireOpen(); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0) return ''; + + $data = $this->stream->read($length); + + if (Runtime\Str\SB\Inspection::length($data) > $length) + throw new StreamException( + 'The underlying stream returned more bytes than requested.' + ); + + if ($data === '' && !$this->stream->eof()) + throw new StreamException( + 'The underlying stream returned no data before reaching EOF.' + ); + + $this->context->update($data); + + return $data; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::requireOpen() To check if the reader is open. + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::read() To read from the underlying stream. + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::eof() To check if the underlying stream is at EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream cannot make progress. + */ + public function contents ():string { + + $this->requireOpen(); + + $contents = ''; + + while (!$this->eof()) { + + $chunk = $this->read(8192); + + if ($chunk === '') break; + + $contents .= $chunk; + + } + + return $contents; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::requireOpen() To check if the reader is open. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function eof ():bool { + + $this->requireOpen(); + + return $this->stream->eof(); + + } + + /** + * ### Gets the current hash digest + * @since 1.0.0 + * + * @uses \FireHub\Foundation\Hash\Context::digest() To get the current hash digest. + * + * @param bool $binary [optional]+ * Whether to return raw binary data. + *
+ * + * @return non-empty-string Hash digest. + */ + public function digest (bool $binary = false):string { + + return $this->context->digest($binary); + + } + + /** + * ### Gets the number of hashed bytes + * @since 1.0.0 + * + * @uses \FireHub\Foundation\Hash\Context::bytes() To get the number of hashed bytes. + * + * @return non-negative-int Number of hashed bytes. + */ + public function bytes ():int { + + return $this->context->bytes(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Requires an open reader + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Reader::isClosed() To check if the reader is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The hashing reader is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Hash/Writer.php b/src/IO/Stream/Hash/Writer.php new file mode 100644 index 0000000..8bf74f9 --- /dev/null +++ b/src/IO/Stream/Hash/Writer.php @@ -0,0 +1,220 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Hash; + +use FireHub\Core\Boundary\IO\Stream\Writable; +use FireHub\Foundation\Hash\Context; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Hash\Algorithm; +use FireHub\Runtime; + +/** + * ### Hashing Stream Writer + * + * Calculates an incremental hash of bytes successfully accepted by an underlying writable stream. + * + * Supports partial writes by hashing only the bytes reported as written. + * + * The underlying stream is borrowed and is not automatically closed. + * @since 1.0.0 + */ +final class Writer implements Writable { + + /** + * ### Hash context + * @since 1.0.0 + */ + private readonly Context $context; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Writable $stream+ * Underlying writable stream. + *
+ * + * @param \FireHub\Runtime\Hash\Algorithm $algorithm [optional]+ * Hashing algorithm. + *
+ * + * @return void + */ + public function __construct ( + private readonly Writable $stream, + Algorithm $algorithm = Algorithm::SHA256 + ) { + + $this->context = new Context($algorithm); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::isClosed() To check if the writer is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::isClosed() To check if the writer is closed. + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::isWritable() To check if the underlying stream is writable. + */ + public function isWritable ():bool { + + return !$this->isClosed() && $this->stream->isWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::requireOpen() To check if the writer is open. + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::size() To get the underlying stream size. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::requireOpen() To check if the writer is open. + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::write() To write to the underlying stream. + * @uses \FireHub\Foundation\Hash\Context::update() To update the hash context. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the data. + * @uses \FireHub\Runtime\Str\SB\Access::part() To extract the written data. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream reports an invalid. + */ + public function write (string $data):int { + + $this->requireOpen(); + + if ($data === '') return 0; + + $written = $this->stream->write($data); + + $length = Runtime\Str\SB\Inspection::length($data); + + if ($written < 0 || $written > $length) + throw new StreamException( + 'The underlying stream reported an invalid write length.' + ); + + if ($written > 0) { + + $this->context->update( + Runtime\Str\SB\Access::part( + $data, + 0, + $written + ) + ); + + } + + return $written; + + } + + /** + * ### Gets the current hash digest + * @since 1.0.0 + * + * @uses \FireHub\Foundation\Hash::digest() To get the hash digest. + * + * @param bool $binary [optional]+ * Whether to return raw binary data. + *
+ * + * @return non-empty-string Hash digest. + */ + public function digest (bool $binary = false):string { + + return $this->context->digest($binary); + + } + + /** + * ### Gets the number of hashed bytes + * @since 1.0.0 + * + * @uses \FireHub\Foundation\Hash::bytes() To get the number of hashed bytes. + * + * @return non-negative-int Number of hashed bytes. + */ + public function bytes ():int { + + return $this->context->bytes(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Requires an open writer + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Hash\Writer::isClosed() To check if the writer is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The hashing writer is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Http.php b/src/IO/Stream/Http.php new file mode 100644 index 0000000..35d0ace --- /dev/null +++ b/src/IO/Stream/Http.php @@ -0,0 +1,135 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### HTTP Stream + * + * Provides a readable stream backed by PHP's http:// and https:// stream wrappers. + * + * Allows reading data from remote HTTP and HTTPS resources using PHP's native stream functionality. + * + * The stream is read-only and does not guarantee seeking or positioning capabilities. + * + * Unlike local filesystem streams, HTTP streams retrieve their contents over a network connection. + * + * Opening the stream may perform network I/O and can fail due to connection errors, timeouts, or HTTP response errors. + * @since 1.0.0 + */ +final class Http extends ResourceStream implements Readable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the HTTP stream. + * @uses \FireHub\Runtime\Str\SB\Search::startsWith() To validate the URI scheme. + * + * @param non-empty-string $uri+ * HTTP or HTTPS URI identifying the remote resource. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the URI scheme is unsupported or the stream cannot be opened. + * + * @return void + */ + public function __construct (string $uri) { + + if ( + !Runtime\Str\SB\Search::startsWith('http://', $uri) + && !Runtime\Str\SB\Search::startsWith('https://', $uri) + ) throw new StreamException( + 'Only HTTP and HTTPS stream URIs are supported.' + ); + + $resource = Runtime\Stream\Handle::open( + $uri, + Runtime\Stream\Enum\OpenMode::READ_BINARY + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open HTTP stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable(): bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read(int $length): string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents(): string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof(): bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Input.php b/src/IO/Stream/Input.php new file mode 100644 index 0000000..7d1d6f8 --- /dev/null +++ b/src/IO/Stream/Input.php @@ -0,0 +1,122 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Input Stream + * + * Provides a readable stream backed by PHP's php://input stream wrapper. + * + * Allows access to the raw body of an incoming HTTP request without requiring the entire content to be loaded into + * memory. + * + * The stream is read-only and does not guarantee seeking or rewinding capabilities. + * + * Unlike php://memory and php://temp, this stream reads data supplied by the PHP execution environment rather than + * storing application-generated content. + * @since 1.0.0 + */ +final class Input extends ResourceStream implements Readable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the php://input stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the input stream cannot be opened. + * + * @return void + */ + public function __construct () { + + $resource = Runtime\Stream\Handle::open( + 'php://input', + Runtime\Stream\Enum\OpenMode::READ_BINARY + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open input stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource has reached the end of input. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Limit/Reader.php b/src/IO/Stream/Limit/Reader.php new file mode 100644 index 0000000..f1f80b3 --- /dev/null +++ b/src/IO/Stream/Limit/Reader.php @@ -0,0 +1,279 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Limit; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Limited Stream Reader + * + * Restricts the number of bytes that can be read from an underlying stream. + * + * The limit applies from the stream's current position. + * + * Reaching the configured limit is treated as EOF, even when the underlying stream contains additional data. + * + * The underlying stream is borrowed and is not automatically closed. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + */ +final class Reader implements Readable { + + /** + * ### Number of bytes consumed + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $consumed = 0; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $stream+ * Underlying readable stream. + *
+ * @param non-negative-int $limit+ * Maximum number of bytes that may be consumed. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the limit is negative. + * + * @return void + */ + public function __construct ( + private readonly Readable $stream, + private readonly int $limit + ) { + + if ($limit < 0) + throw new StreamException( + 'Read limit cannot be negative.' + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::isClosed() To check if the reader is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::isClosed() To check if the reader is closed. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the underlying stream is readable. + */ + public function isReadable ():bool { + + return !$this->isClosed() + && $this->stream->isReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::requireOpen() To check if the reader is open. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return null; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::requireOpen() To check if the reader is open. + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::remaining() To determine the remaining allowance. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read from the underlying stream. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check for EOF. + * @uses \FireHub\Runtime\Math::min() To clamp the requested length. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To count the received bytes. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the length is invalid, the reader is + * closed, or the underlying stream violates the read contract. + */ + public function read (int $length):string { + + $this->requireOpen(); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0 || $this->remaining() === 0) + return ''; + + $requested = Runtime\Math::min( + $length, + $this->remaining() + ); + + $chunk = $this->stream->read($requested); + + $received = Runtime\Str\SB\Inspection::length($chunk); + + if ($received > $requested) + throw new StreamException( + 'The underlying stream returned more bytes than requested.' + ); + + if ($chunk === '' && !$this->stream->eof()) + throw new StreamException( + 'The underlying stream returned no data before reaching EOF.' + ); + + $this->consumed += $received; + + return $chunk; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::requireOpen() To check if the reader is open. + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::eof() To check for EOF. + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::read() To read the next chunk. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + $this->requireOpen(); + + $contents = ''; + + while (!$this->eof()) { + + $chunk = $this->read(8192); + + if ($chunk === '') break; + + $contents .= $chunk; + + } + + return $contents; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::requireOpen() To check if the reader is open. + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::remaining() To check the remaining allowance. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function eof ():bool { + + $this->requireOpen(); + + return $this->remaining() === 0 || $this->stream->eof(); + + } + + /** + * ### Gets consumed bytes + * @since 1.0.0 + * + * @return non-negative-int Number of bytes consumed through this decorator. + */ + public function consumed ():int { + + return $this->consumed; + + } + + /** + * ### Gets remaining allowance + * @since 1.0.0 + * + * @return non-negative-int Number of bytes remaining before reaching the limit. + */ + public function remaining ():int { + + /** @var non-negative-int */ + return $this->limit - $this->consumed; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Requires an open reader + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Reader::isClosed() To check if the reader is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The limited reader is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Limit/Writer.php b/src/IO/Stream/Limit/Writer.php new file mode 100644 index 0000000..e8f8229 --- /dev/null +++ b/src/IO/Stream/Limit/Writer.php @@ -0,0 +1,226 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Limit; + +use FireHub\Core\Boundary\IO\Stream\Writable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Limited Stream Writer + * + * Restricts the total number of bytes accepted by an underlying stream. + * + * Writes exceeding the remaining allowance are truncated. + * + * Partial writes from the underlying stream are preserved. + * + * Once the limit has been reached, write() returns zero. + * + * The underlying stream is borrowed and is not automatically closed. + * @since 1.0.0 + */ +final class Writer implements Writable { + + /** + * ### Number of accepted bytes + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $written = 0; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Writable $stream+ * Underlying writable stream. + *
+ * @param non-negative-int $limit+ * Maximum number of bytes accepted by this decorator. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the limit is negative. + * + * @return void + */ + public function __construct ( + private readonly Writable $stream, + private readonly int $limit + ) { + + if ($limit < 0) + throw new StreamException( + 'Write limit cannot be negative.' + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Writer::isClosed() To check if the writer is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Writer::remaining() To determine the remaining allowance. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isWritable() To check if the underlying stream is writable. + * @uses \FireHub\Foundation\IO\Stream\Limit\Writer::isClosed() To check if the writer is closed. + */ + public function isWritable ():bool { + + return !$this->isClosed() + && $this->remaining() > 0 + && $this->stream->isWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Writer::requireOpen() To check if the writer is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::size() To get the size of the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Writer::requireOpen() To check if the writer is open. + * @uses \FireHub\Foundation\IO\Stream\Limit\Writer::remaining() To determine the remaining allowance. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::write() To write data. + * @uses \FireHub\Runtime\Math::min() To clamp the write length. + * @uses \FireHub\Runtime\Str\SB\Access::part() To extract the permitted data. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To count bytes. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed or the underlying + * stream reports an invalid write length. + */ + public function write (string $data):int { + + $this->requireOpen(); + + if ($data === '' || $this->remaining() === 0) + return 0; + + $length = Runtime\Math::min( + Runtime\Str\SB\Inspection::length($data), + $this->remaining() + ); + + $chunk = Runtime\Str\SB\Access::part( + $data, + 0, + $length + ); + + $written = $this->stream->write($chunk); + + if ($written < 0 || $written > $length) + throw new StreamException( + 'The underlying stream reported an invalid write length.' + ); + + $this->written += $written; + + return $written; + + } + + /** + * ### Gets accepted bytes + * @since 1.0.0 + * + * @return non-negative-int Number of bytes accepted by the underlying stream. + */ + public function written ():int { + + return $this->written; + + } + + /** + * ### Gets remaining allowance + * @since 1.0.0 + * + * @return non-negative-int Number of bytes remaining before reaching the limit. + */ + public function remaining ():int { + + /** @var non-negative-int */ + return $this->limit - $this->written; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Requires an open writer + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Limit\Writer::isClosed() To check if the writer is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The limited writer is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Memory.php b/src/IO/Stream/Memory.php new file mode 100644 index 0000000..21a57ef --- /dev/null +++ b/src/IO/Stream/Memory.php @@ -0,0 +1,212 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Positionable, Readable, Seekable, Writable +}; +use FireHub\Core\Type\IO\SeekOrigin; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Memory Stream + * + * Provides a readable, writable, and seekable stream backed by PHP's php://memory stream wrapper. + * + * All stream contents are stored in memory and discarded when the underlying resource is closed. + * + * Unlike php://temp, this stream does not automatically spill its contents to a temporary file. + * @since 1.0.0 + */ +final class Memory extends ResourceStream implements Positionable, Seekable, Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the php://memory stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream cannot be opened. + * + * @return void + */ + public function __construct () { + + $resource = Runtime\Stream\Handle::open( + 'php://memory', + Runtime\Stream\Enum\OpenMode::READ_WRITE_BINARY + ); + + if ($resource === false) { + throw new StreamException( + 'Unable to open memory stream.' + ); + } + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::resourceIsSeekable() To check if the resource is seekable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isSeekable ():bool { + + return $this->resourceIsSeekable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::readResourceContents() To read the entire contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::tellResource() To get the current position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the position cannot be determined. + */ + public function tell ():int { + + return $this->tellResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::seekResource() To seek to a specific position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function seek (int $offset, SeekOrigin $origin = SeekOrigin::START):void { + + $this->seekResource($offset, $origin); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::rewindResource() To rewind the resource to the beginning. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function rewind ():void { + + $this->rewindResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Resource::resourceEof() To check if the resource is at the end of the stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Output.php b/src/IO/Stream/Output.php new file mode 100644 index 0000000..4dc3145 --- /dev/null +++ b/src/IO/Stream/Output.php @@ -0,0 +1,93 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\Writable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Output Stream + * + * Provides a writable stream backed by PHP's php://output stream wrapper. + * + * Writes data directly to PHP's output mechanism, allowing content to be sent to the client or captured by an active + * output buffer. + * + * Unlike php://memory and php://temp, this stream does not store written content for subsequent reading. + * + * The stream is write-only and does not support seeking or rewinding. + * @since 1.0.0 + */ +final class Output extends ResourceStream implements Writable { + + /** + * ### Constructor + * + * Opens PHP's output stream for writing. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the php://output stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the output stream cannot be opened. + * + * @return void + */ + public function __construct () { + + $resource = Runtime\Stream\Handle::open( + 'php://output', + Runtime\Stream\Enum\OpenMode::WRITE_BINARY + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open output stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Ownership.php b/src/IO/Stream/Ownership.php new file mode 100644 index 0000000..7b2f951 --- /dev/null +++ b/src/IO/Stream/Ownership.php @@ -0,0 +1,40 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +/** + * ### Stream Resource Ownership + * + * Defines whether a stream implementation is responsible for closing its underlying resource. + * @since 1.0.0 + */ +enum Ownership { + + /** + * ### Owned resource + * + * The stream is responsible for closing the underlying resource. + * @since 1.0.0 + */ + case OWNED; + + /** + * ### Borrowed resource + * + * The stream must not close the underlying resource. + * @since 1.0.0 + */ + case BORROWED; + +} \ No newline at end of file diff --git a/src/IO/Stream/Phar.php b/src/IO/Stream/Phar.php new file mode 100644 index 0000000..3ffad6a --- /dev/null +++ b/src/IO/Stream/Phar.php @@ -0,0 +1,189 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Writable +}; +use FireHub\Core\Meta\Enum\Side; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Stream\Enum\OpenMode; +use FireHub\Runtime; + +/** + * ### PHAR Archive Entry Stream + * + * Provides a readable and writable stream backed by PHP's phar:// stream wrapper. + * + * Allows reading and writing individual files stored inside PHAR-compatible archives without extracting the entire + * archive. + * + * Reading and writing capabilities depend on the selected opening mode, archive format, and PHP configuration. + * + * Writing to executable PHAR archives may be restricted by the phar.readonly configuration directive. + * + * This abstraction does not expose archive creation, deletion, signing, or metadata management operations. + * + * Requires the PHP Phar extension. + * @since 1.0.0 + */ +final class Phar extends ResourceStream implements Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the PHAR archive entry. + * @uses \FireHub\Runtime\System\Extension::hasExtension() To validate the extension availability. + * + * @param non-empty-string $archive+ * Path to the PHAR-compatible archive. + *
+ * @param non-empty-string $entry+ * Path to the file inside the archive. + *
+ * @param \FireHub\Runtime\Stream\Enum\OpenMode $mode [optional]+ * Stream opening mode. + * + * Defaults to READ_BINARY. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the Phar extension is unavailable, + * the archive or entry path is invalid, or the stream cannot be opened. + * + * @return void + * + */ + public function __construct (string $archive, string $entry, OpenMode $mode = OpenMode::READ_BINARY) { + + if (!Runtime\System\Extension::hasExtension('phar')) + throw new StreamException( + 'The Phar extension is required to open PHAR archive streams.' + ); + + if ($archive === '') + throw new StreamException( + 'The PHAR archive path cannot be empty.' + ); + + if ($entry === '') + throw new StreamException( + 'The PHAR archive entry path cannot be empty.' + ); + + $resource = Runtime\Stream\Handle::open( + 'phar://' . $archive . '/' . Runtime\Str\SB\Transform::trim($entry, Side::LEFT, '/'), + $mode + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open PHAR archive entry stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Progress/Reader.php b/src/IO/Stream/Progress/Reader.php new file mode 100644 index 0000000..8a5bd64 --- /dev/null +++ b/src/IO/Stream/Progress/Reader.php @@ -0,0 +1,351 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Progress; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; +use Closure; + +/** + * ### Progress Stream Reader + * + * Tracks the number of bytes successfully read from an underlying stream. + * + * Supports optional progress notifications and total-size tracking. + * + * Only bytes returned by successful read operations are counted. + * + * The underlying stream is borrowed and is not automatically closed. + * @since 1.0.0 + */ +final class Reader implements Readable { + + /** + * ### Processed bytes + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $processed = 0; + + /** + * ### Progress callback + * @since 1.0.0 + * + * @var null|Closure(int, ?int):void + */ + private ?Closure $callback = null; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $stream+ * Underlying readable stream. + *
+ * @param null|non-negative-int $total [optional]+ * Expected total number of bytes. Null means unknown. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If total is negative. + * + * @return void + */ + public function __construct ( + private readonly Readable $stream, + private readonly ?int $total = null + ) { + + if ($total !== null && $total < 0) + throw new StreamException( + 'Total bytes cannot be negative.' + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isClosed() To check if the underlying stream is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the underlying stream is readable. + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::isClosed() To check if the reader is closed. + */ + public function isReadable ():bool { + + return !$this->isClosed() && $this->stream->isReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::requireOpen() To ensure the stream is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::size() To get the underlying stream size. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::requireOpen() To ensure the stream is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read from the underlying stream. + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::notify() To notify the progress callback. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the returned data. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed, or the underlying stream + * returns no data before reaching EOF. + */ + public function read (int $length):string { + + $this->requireOpen(); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0) return ''; + + $data = $this->stream->read($length); + + $received = Runtime\Str\SB\Inspection::length($data); + + if ($received > $length) + throw new StreamException( + 'The underlying stream returned more bytes than requested.' + ); + + if ($data === '' && !$this->stream->eof()) + throw new StreamException( + 'The underlying stream returned no data before reaching EOF.' + ); + + if ($received > 0) { + + $this->processed += $received; + + $this->notify(); + + } + + return $data; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::requireOpen() To ensure the stream is open. + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::read() To read the stream. + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::eof() To check if EOF is reached. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function contents ():string { + + $this->requireOpen(); + + $contents = ''; + + while (!$this->eof()) { + + $chunk = $this->read(8192); + + if ($chunk === '') break; + + $contents .= $chunk; + + } + + return $contents; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::requireOpen() To ensure the stream is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if the underlying stream is at EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + $this->requireOpen(); + + return $this->stream->eof(); + + } + + /** + * ### Gets processed bytes + * @since 1.0.0 + * + * @return non-negative-int Number of successfully read bytes. + */ + public function processed ():int { + + return $this->processed; + + } + + /** + * ### Gets expected total bytes + * @since 1.0.0 + * + * @return null|non-negative-int Expected total bytes. + */ + public function total ():?int { + + return $this->total; + + } + + /** + * ### Gets remaining bytes + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Math::max() To ensure the result is non-negative. + * + * @return null|non-negative-int Remaining expected bytes. + */ + public function remaining ():?int { + + if ($this->total === null) return null; + + /** @var non-negative-int */ + return Runtime\Math::max( + 0, + $this->total - $this->processed + ); + + } + + /** + * ### Gets progress percentage + * @since 1.0.0 + * + * @return null|float Progress percentage, or null if total is unknown. + */ + public function percentage ():?float { + + if ($this->total === null) return null; + + if ($this->total === 0) + return $this->processed === 0 ? 100.0 : null; + + return $this->processed / $this->total * 100; + + } + + /** + * ### Registers a progress callback + * + * The callback receives the number of processed bytes and the expected total number of bytes. + * @since 1.0.0 + * + * @param Closure(int, ?int):void $callback + * Progress callback. + * + * @return self Current reader. + */ + public function onProgress (Closure $callback):self { + + $this->callback = $callback; + + return $this; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Notifies the progress callback + * @since 1.0.0 + * + * @return void + */ + private function notify ():void { + + if ($this->callback !== null) + ($this->callback)($this->processed, $this->total); + + } + + /** + * ### Requires an open reader + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Reader::isClosed() To check if the reader is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The progress reader is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Progress/Writer.php b/src/IO/Stream/Progress/Writer.php new file mode 100644 index 0000000..026b3dd --- /dev/null +++ b/src/IO/Stream/Progress/Writer.php @@ -0,0 +1,288 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Progress; + +use FireHub\Core\Boundary\IO\Stream\Writable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; +use Closure; + +/** + * ### Progress Stream Writer + * + * Tracks the number of bytes successfully accepted by an underlying writable stream. + * + * Supports partial writes and optional progress notifications. + * + * The underlying stream is borrowed and is not automatically closed. + * @since 1.0.0 + */ +final class Writer implements Writable { + + /** + * ### Processed bytes + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $processed = 0; + + /** + * ### Progress callback + * @since 1.0.0 + * + * @var null|Closure(int, ?int):void + */ + private ?Closure $callback = null; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Writable $stream+ * Underlying writable stream. + *
+ * @param null|non-negative-int $total [optional]+ * Expected total number of bytes. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If total is negative. + * + * @return void + */ + public function __construct ( + private readonly Writable $stream, + private readonly ?int $total = null + ) { + + if ($total !== null && $total < 0) + throw new StreamException( + 'Total bytes cannot be negative.' + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isClosed() To check if the underlying stream is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isWritable() To check if the underlying stream is writable. + * @uses \FireHub\Foundation\IO\Stream\Progress\Writer::isClosed() To check if the writer is closed. + */ + public function isWritable ():bool { + + return !$this->isClosed() && $this->stream->isWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Writer::requireOpen() To check if the writer is open. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::size() To get the size of the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + * + */ + public function size ():?int { + + $this->requireOpen(); + + return $this->stream->size(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Writer::requireOpen() To check if the writer is open. + * @uses \FireHub\Foundation\IO\Stream\Progress\Writer::write() To write to the underlying stream. + * @uses \FireHub\Foundation\IO\Stream\Progress\Writer::notify() To notify the progress callback. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the string. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream cannot make progress. + */ + public function write (string $data):int { + + $this->requireOpen(); + + if ($data === '') return 0; + + $written = $this->stream->write($data); + + $length = Runtime\Str\SB\Inspection::length($data); + + if ($written < 0 || $written > $length) + throw new StreamException( + 'The underlying stream reported an invalid write length.' + ); + + if ($written > 0) { + + $this->processed += $written; + + $this->notify(); + + } + + return $written; + + } + + /** + * ### Gets processed bytes + * @since 1.0.0 + * + * @return non-negative-int Number of successfully written bytes. + */ + public function processed ():int { + + return $this->processed; + + } + + /** + * ### Gets expected total bytes + * @since 1.0.0 + * + * @return null|non-negative-int Expected total bytes. + */ + public function total ():?int { + + return $this->total; + + } + + /** + * ### Gets remaining bytes + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Math::max() To prevent negative values. + * + * @return null|non-negative-int Remaining expected bytes. + */ + public function remaining ():?int { + + if ($this->total === null) return null; + + /** @var non-negative-int */ + return Runtime\Math::max( + 0, + $this->total - $this->processed + ); + + } + + /** + * ### Gets progress percentage + * @since 1.0.0 + * + * @return null|float Progress percentage, or null if total is unknown. + */ + public function percentage ():?float { + + if ($this->total === null) return null; + + if ($this->total === 0) + return $this->processed === 0 ? 100.0 : null; + + return $this->processed / $this->total * 100; + + } + + /** + * ### Registers a progress callback + * @since 1.0.0 + * + * @param Closure(int, ?int):void $callback + * Progress callback. + * + * @return self Current writer. + */ + public function onProgress (Closure $callback):self { + + $this->callback = $callback; + + return $this; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Notifies the progress callback + * @since 1.0.0 + * + * @return void + */ + private function notify ():void { + + if ($this->callback !== null) + ($this->callback)($this->processed, $this->total); + + } + + /** + * ### Requires an open writer + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Progress\Writer::isClosed() To check if the writer is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The progress writer is closed.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Pump.php b/src/IO/Stream/Pump.php new file mode 100644 index 0000000..6714c14 --- /dev/null +++ b/src/IO/Stream/Pump.php @@ -0,0 +1,388 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Writable +}; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Stream Pump + * + * Transfers data incrementally between readable and writable streams. + * + * Maintains pending data between transfer steps to support partial writes. + * + * Each advance operation performs at most one read or one writing. + * + * The source and destination remain owned by their original owners. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + */ +final class Pump { + + /** + * ### Pending data + * @since 1.0.0 + */ + private string $buffer = ''; + + /** + * ### Position within pending data + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $position = 0; + + /** + * ### Number of transferred bytes + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $transferred = 0; + + /** + * ### Completion state + * @since 1.0.0 + */ + private bool $complete; + + /** + * ### Cancellation state + * @since 1.0.0 + */ + private bool $cancelled = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the source stream is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isWritable() To check if the destination stream is writable. + * @uses \FireHub\Core\Boundary\IO\Stream::isClosed() To check if the source or destination stream is closed. + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $source+ * Source stream. + *
+ * @param \FireHub\Core\Boundary\IO\Stream\Writable $destination+ * Destination stream. + *
+ * @param positive-int $buffer_size [optional]+ * Maximum number of bytes requested per read operation. + *
+ * @param null|non-negative-int $limit [optional]+ * Maximum number of bytes to transfer. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the configuration is invalid. + * + * @return void + */ + public function __construct ( + private readonly Readable $source, + private readonly Writable $destination, + private readonly int $buffer_size = 65536, + private readonly ?int $limit = null + ) { + + if ($buffer_size <= 0) + throw new StreamException( + 'Buffer size must be greater than zero.' + ); + + if ($limit !== null && $limit < 0) + throw new StreamException( + 'Transfer limit cannot be negative.' + ); + + if ($source === $destination) + throw new StreamException( + 'Source and destination cannot be the same stream.' + ); + + if ($source->isClosed() || !$source->isReadable()) + throw new StreamException( + 'The source stream must be open and readable.' + ); + + if ($destination->isClosed() || !$destination->isWritable()) + throw new StreamException( + 'The destination stream must be open and writable.' + ); + + $this->complete = $limit === 0; + + } + + /** + * ### Advances the transfer + * + * Performs at most one underlying read or write operation. + * + * Pending data is always written before reading additional data. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Pump::writePending() To write pending data. + * @uses \FireHub\Foundation\IO\Stream\Pump::pending() To get the number of pending bytes. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isClosed() To check if the source stream is closed. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the source stream is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if the source stream is at EOF. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read from the source stream. + * @uses \FireHub\Runtime\Math::min() To clamp the buffer size to the limit. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the read data. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the transfer cannot make progress. + * + * @return non-negative-int Number of bytes written during this step. + */ + public function advance ():int { + + if ($this->cancelled) + throw new StreamException( + 'The stream pump has been cancelled.' + ); + + if ($this->complete) return 0; + + if ($this->pending() > 0) + return $this->writePending(); + + if ($this->limit !== null && $this->transferred >= $this->limit) { + + $this->complete = true; + + return 0; + + } + + if ($this->source->isClosed() || !$this->source->isReadable()) + throw new StreamException( + 'The source stream is not readable.' + ); + + if ($this->source->eof()) { + + $this->complete = true; + + return 0; + + } + + /** @var non-negative-int $length */ + $length = $this->limit === null + ? $this->buffer_size + : Runtime\Math::min( + $this->buffer_size, + $this->limit - $this->transferred + ); + + $chunk = $this->source->read($length); + + $received = Runtime\Str\SB\Inspection::length($chunk); + + if ($received > $length) + throw new StreamException( + 'The source stream returned more bytes than requested.' + ); + + if ($chunk === '') { + + if ($this->source->eof()) { // @phpstan-ignore if.alwaysFalse + + $this->complete = true; + + return 0; + + } + + throw new StreamException( + 'The source stream returned no data before reaching EOF.' + ); + + } + + $this->buffer = $chunk; + $this->position = 0; + + return 0; + + } + + /** + * ### Runs the transfer to completion + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Pump::advance() To perform the transfer step. + * @uses \FireHub\Foundation\IO\Stream\Pump::isComplete() To check if the transfer is complete. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the transfer fails or has been cancelled. + * + * @return non-negative-int Total number of transferred bytes. + */ + public function run ():int { + + while (!$this->isComplete()) + $this->advance(); + + return $this->transferred; + + } + + /** + * ### Determines whether the transfer is complete + * @since 1.0.0 + * + * @return bool True if the transfer has completed. + */ + public function isComplete ():bool { + + return $this->complete; + + } + + /** + * ### Gets the transferred byte count + * @since 1.0.0 + * + * @return non-negative-int Number of bytes written. + */ + public function transferred ():int { + + return $this->transferred; + + } + + /** + * ### Gets the number of pending bytes + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the pending data. + * + * @return non-negative-int Number of bytes awaiting transfer. + */ + public function pending ():int { + + /** @var non-negative-int */ + return Runtime\Str\SB\Inspection::length($this->buffer) + - $this->position; + + } + + /** + * ### Gets the remaining transfer allowance + * @since 1.0.0 + * + * @return null|non-negative-int Remaining transfer allowance. + */ + public function remaining ():?int { + + if ($this->limit === null) return null; + + /** @var non-negative-int */ + return $this->limit - $this->transferred; + + } + + /** + * ### Cancels the transfer + * + * Discards pending data without closing the underlying streams. + * @since 1.0.0 + * + * @return void + */ + public function cancel ():void { + + if ($this->complete || $this->cancelled) return; + + $this->cancelled = true; + + $this->buffer = ''; + $this->position = 0; + + } + + /** + * ### Determines whether the transfer was canceled + * @since 1.0.0 + * + * @return bool True if the transfer was cancelled. + */ + public function isCancelled ():bool { + + return $this->cancelled; + + } + + /** + * ### Writes pending data + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Pump::pending() To get the number of pending bytes. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isClosed() To check if the destination stream is closed. + * @uses \FireHub\Core\Boundary\IO\Stream\Writable::isWritable() To check if the destination stream is writable. + * @uses \FireHub\Runtime\Str\SB\Access::part() To get the pending data. + * @uses \FireHub\Core\Boundary\IO\Stream::write() To write to the destination stream. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the written data. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the destination cannot accept data. + * + * @return positive-int Number of bytes written. + */ + private function writePending ():int { + + if ($this->destination->isClosed() || !$this->destination->isWritable()) + throw new StreamException( + 'The destination stream is not writable.' + ); + + $remaining = Runtime\Str\SB\Access::part( + $this->buffer, + $this->position + ); + + $written = $this->destination->write($remaining); + + $available = Runtime\Str\SB\Inspection::length($remaining); + + if ($written <= 0 || $written > $available) + throw new StreamException( + 'The destination stream reported an invalid write length.' + ); + + $this->position += $written; + $this->transferred += $written; + + if ($this->pending() === 0) { + + $this->buffer = ''; + $this->position = 0; + + if ( + $this->limit !== null + && $this->transferred >= $this->limit + ) $this->complete = true; + + } + + return $written; + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Reader.php b/src/IO/Stream/Reader.php new file mode 100644 index 0000000..70a69a5 --- /dev/null +++ b/src/IO/Stream/Reader.php @@ -0,0 +1,99 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\DataStructure\Stream; +use FireHub\Foundation\IO\Stream\Source\ { + Byte, Chunk, Line +}; + +/** + * ### Stream Reader + * + * Provides factories for creating lazy data structure streams from readable I/O streams. + * @since 1.0.0 + */ +final readonly class Reader { + + /** + * ### Chunks + * @since 1.0.0 + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable $stream+ * The readable stream used as the source of bytes. + *
+ * @param positive-int $size [optional]+ * Maximum number of bytes per chunk. + * + * Defaults to 8192. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the chunk size is not positive. + * + * @return \FireHub\Foundation\DataStructure\Stream+ * Source stream. + *
+ * @param positive-int $chunk_size [optional]+ * Maximum bytes read per operation. + * + * Defaults to 8192. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the chunk size is invalid. + * + * @return \FireHub\Foundation\DataStructure\Stream+ * Source stream. + *
+ * @param positive-int $chunk_size [optional]+ * Number of bytes read per operation. + * + * Defaults to 8192. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the chunk size is invalid. + * + * @return \FireHub\Foundation\DataStructure\Stream+ * Native PHP stream resource. + *
+ * @param \FireHub\Foundation\IO\Stream\Ownership $ownership [optional]+ * Determines whether the stream owns the underlying resource. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the resource is not a valid PHP stream. + * + * @return void + */ + protected function __construct (mixed $resource, Ownership $ownership = Ownership::BORROWED) { + + if ( + !Runtime\DataIs::resource($resource) + || Runtime\ResourceManager::type($resource) !== Runtime\Type\Resource::STREAM + ) throw new StreamException( + 'The supplied resource must be a valid PHP stream.' + ); + + $this->resource = $resource; + $this->ownership = $ownership; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Runtime\DataIs::resource() To validate the resource type. + */ + final public function isClosed ():bool { + + return !Runtime\DataIs::resource($this->resource); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::close() To close the underlying resource. + * @uses \FireHub\Runtime\DataIs::resource() To validate the resource type. + * @uses \FireHub\Foundation\IO\Stream\Filter\Attachment::remove() To remove the stream filter. + * @uses \FireHub\Foundation\IO\Stream\Filter\Attachment::invalidate() To invalidate the stream filter. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If removing the filter fails. + */ + final public function close ():void { + + if ($this->resource === null) return; + + $resource = $this->resource; + + if ( + $this->ownership === Ownership::BORROWED + && Runtime\DataIs::resource($resource) + ) foreach ($this->filters as $attachment) + $attachment->remove(); + + $this->resource = null; + + if ( + $this->ownership === Ownership::OWNED + && Runtime\DataIs::resource($resource) + ) Runtime\Stream\Handle::close($resource); + + foreach ($this->filters as $attachment) + $attachment->invalidate(); + + $this->filters = []; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Metadata::get() To get stream metadata. + * @uses \FireHub\Runtime\Stream\Metadata::statistics() To get stream statistics. + * @uses \FireHub\Runtime\DataIs::int() To validate the size type. + * @uses \FireHub\Runtime\DataIs::string() To validate the URI type. + * @uses \FireHub\Runtime\Str\SB\Search::startsWith() To check if the URI starts with a specific prefix. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function size ():?int { + + $resource = $this->requireResource(); + + $metadata = Runtime\Stream\Metadata::get($resource); + + $wrapper = $metadata['wrapper_type'] ?? null; + $uri = $metadata['uri'] ?? null; + + $supported = $wrapper === 'plainfile' + || ( + $wrapper === 'PHP' + && Runtime\DataIs::string($uri) + && ( + Runtime\Str\SB\Search::startsWith('php://memory', $uri) + || Runtime\Str\SB\Search::startsWith('php://temp', $uri) + ) + ); + + if (!$supported) return null; + + $stat = Runtime\Stream\Metadata::statistics($resource); + + if ($stat === false) return null; + + $size = $stat['size'] ?? null; + + return Runtime\DataIs::int($size) && $size >= 0 + ? $size : null; + + } + + /** + * ### Gets the active native stream resource + * @since 1.0.0 + * + * @uses \FireHub\Runtime\DataIs::resource() To validate the resource type. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + * + * @return resource Active PHP stream resource. + */ + final protected function requireResource ():mixed { + + $resource = $this->resource; + + if (!Runtime\DataIs::resource($resource)) + throw new StreamException( + 'The stream is closed.' + ); + + return $resource; + + } + + /** + * ### Checks whether the stream currently supports reading + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsClosed() To check if the stream is closed. + * @uses \FireHub\Runtime\Stream\Metadata::get() To get stream metadata. + * @uses \FireHub\Runtime\Str\SB\Search::contains() To check if the mode contains a specific substring. + * @uses \FireHub\Runtime\Str\SB\Search::startsWith() To check if the mode starts with a specific prefix. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + * + * @return bool True if the stream is readable. + */ + final protected function resourceIsReadable ():bool { + + if ($this->isClosed()) return false; + + $metadata = Runtime\Stream\Metadata::get( + $this->requireResource() + ); + + /** @var string $mode */ + $mode = $metadata['mode'] ?? ''; + + return Runtime\Str\SB\Search::contains('+', $mode) + || Runtime\Str\SB\Search::startsWith('r', $mode); + + } + + /** + * ### Checks whether the stream currently supports writing + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsClosed() To check if the stream is closed. + * @uses \FireHub\Runtime\Stream\Metadata::get() To get stream metadata. + * @uses \FireHub\Runtime\Str\SB\Search::contains() To check if the mode contains a specific substring. + * @uses \FireHub\Runtime\Str\SB\Search::startsWith() To check if the mode starts with a specific prefix. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + * + * @return bool True if the stream is writable. + */ + final protected function resourceIsWritable ():bool { + + if ($this->isClosed()) return false; + + $metadata = Runtime\Stream\Metadata::get( + $this->requireResource() + ); + + /** @var string $mode */ + $mode = $metadata['mode'] ?? ''; + + return Runtime\Str\SB\Search::contains('+', $mode) + || Runtime\Str\SB\Search::startsWith('w', $mode) + || Runtime\Str\SB\Search::startsWith('a', $mode) + || Runtime\Str\SB\Search::startsWith('x', $mode) + || Runtime\Str\SB\Search::startsWith('c', $mode); + + } + + /** + * ### Checks whether the stream currently supports seeking + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsClosed() To check if the stream is closed. + * @uses \FireHub\Runtime\Stream\Metadata::get() To get stream metadata. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + * + * @return bool True if the stream is seekable. + */ + final protected function resourceIsSeekable ():bool { + + if ($this->isClosed()) return false; + + $metadata = Runtime\Stream\Metadata::get( + $this->requireResource() + ); + + return ($metadata['seekable'] ?? false) === true; + + } + + /** + * ### Reads bytes from the resource + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsClosed() To check if the stream is closed. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the stream is readable. + * @uses \FireHub\Runtime\Stream\Read::bytes() To read bytes from the stream. + * + * @param non-negative-int $length+ * Maximum number of bytes to read. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + * + * @return string Data read from the stream. + */ + final protected function readResource (int $length):string { + + $resource = $this->requireResource(); + + if (!$this->resourceIsReadable()) + throw new StreamException( + 'The stream is not readable.' + ); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0) return ''; + + $data = Runtime\Stream\Read::bytes($resource, $length); + + if ($data === false) + throw new StreamException( + 'Unable to read from the stream.' + ); + + return $data; + + } + + /** + * ### Reads the remaining resource contents + * + * Reads from the current position to the end of the stream. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsClosed() To check if the stream is closed. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the stream is readable. + * @uses \FireHub\Runtime\Stream\Read::contents() To read the stream contents. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + * + * @return string Remaining stream contents. + */ + final protected function readResourceContents ():string { + + $resource = $this->requireResource(); + + if (!$this->resourceIsReadable()) + throw new StreamException( + 'The stream is not readable.' + ); + + $contents = Runtime\Stream\Read::contents($resource); + + if ($contents === false) + throw new StreamException( + 'Unable to read stream contents.' + ); + + return $contents; + + } + + /** + * ### Writes bytes to the resource + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsClosed() To check if the stream is closed. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the stream is writable. + * @uses \FireHub\Runtime\Stream\Write::bytes() To write bytes to the stream. + * + * @return non-negative-int+ * Number of bytes written. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + * + * @return non-negative-int Number of bytes written. + */ + final protected function writeResource (string $data):int { + + $resource = $this->requireResource(); + + if (!$this->resourceIsWritable()) + throw new StreamException( + 'The stream is not writable.' + ); + + if ($data === '') return 0; + + $written = Runtime\Stream\Write::bytes($resource, $data); + + if ($written === false) + throw new StreamException( + 'Unable to write to the stream.' + ); + + return $written; + + } + + /** + * ### Gets the current resource position + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsClosed() To check if the stream is closed. + * @uses \FireHub\Runtime\Stream\Position::tell() To get the current stream position. + * + * @return non-negative-int+ * Current byte offset. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the position cannot be determined. + */ + final protected function tellResource ():int { + + $position = Runtime\Stream\Position::tell( + $this->requireResource() + ); + + if ($position === false || $position < 0) + throw new StreamException( + 'Unable to determine the stream position.' + ); + + return $position; + + } + + /** + * ### Moves the resource position + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::requireResource() To require the stream resource. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsSeekable() To check if the stream is seekable. + * @uses \FireHub\Runtime\Stream\Position::seek() To move the stream position. + * + * @param int $offset+ * Offset to move the position. + *
+ * @param \FireHub\Core\Type\IO\SeekOrigin $origin [optional]+ * Reference position used to calculate the new position. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + * + * @return void + */ + final protected function seekResource (int $offset, SeekOrigin $origin = SeekOrigin::START):void { + + $resource = $this->requireResource(); + + if (!$this->resourceIsSeekable()) + throw new StreamException( + 'The stream is not seekable.' + ); + + if (Runtime\Stream\Position::seek($resource, $offset, $origin) !== 0) + throw new StreamException( + 'Unable to seek within the stream.' + ); + + } + + /** + * ### Rewinds the resource + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::seekResource() To move the stream position to the start. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + * + * @return void + */ + final protected function rewindResource ():void { + + $this->seekResource(0); + + } + + /** + * ### Checks whether the resource has reached EOF + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::requireResource() To require the stream resource. + * @uses \FireHub\Runtime\Stream\Position::eof() To check if EOF has been reached. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + * + * @return bool True if EOF has been reached. + */ + final protected function resourceEof ():bool { + + return Runtime\Stream\Position::eof( + $this->requireResource() + ); + + } + + /** + * ### Appends a filter to the stream + * + * Adds a native PHP stream filter to the end of the specified filter chain. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Filter::append() To append the native stream filter. + * + * @param non-empty-string $name+ * Name of the registered stream filter. + *
+ * @param \FireHub\Runtime\Stream\Enum\FilterFlag $flag [optional]+ * Determines whether the filter processes reading, writing, or both. + *
+ * @param mixed $params [optional]+ * Optional filter parameters. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If attaching the filter fails. + * + * @return \FireHub\Foundation\IO\Stream\Filter\Attachment Attached filter. + */ + final public function appendFilter (string $name, FilterFlag $flag = FilterFlag::READ_WRITE, mixed $params = null):Attachment { + + $resource = Runtime\Stream\Filter::append( + $this->requireResource(), + $name, + $flag, + $params + ); + + if ($resource === false) + throw new StreamException( + 'Unable to append stream filter.' + ); + + $id = ++$this->next_filter_id; + + $attachment = new Attachment( + $resource, + function () use ($id):void { + + unset($this->filters[$id]); + + } + ); + + $this->filters[$id] = $attachment; + + return $attachment; + + } + + /** + * ### Prepends a filter to the stream + * + * Adds a native PHP stream filter to the beginning of the specified filter chain. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Filter::prepend() To prepend the native stream filter. + * + * @param non-empty-string $name+ * Name of the registered stream filter. + *
+ * @param \FireHub\Runtime\Stream\Enum\FilterFlag $flag [optional]+ * Determines whether the filter processes reading, writing, or both. + *
+ * @param mixed $params [optional]+ * Optional filter parameters. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If attaching the filter fails. + * + * @return \FireHub\Foundation\IO\Stream\Filter\Attachment Attached filter. + */ + final public function prependFilter (string $name, FilterFlag $flag = FilterFlag::READ_WRITE, mixed $params = null):Attachment { + + $resource = Runtime\Stream\Filter::prepend( + $this->requireResource(), + $name, + $flag, + $params + ); + + if ($resource === false) + throw new StreamException( + 'Unable to prepend stream filter.' + ); + + $id = ++$this->next_filter_id; + + $attachment = new Attachment( + $resource, + function () use ($id):void { + + unset($this->filters[$id]); + + } + ); + + $this->filters[$id] = $attachment; + + return $attachment; + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Slice/Reader.php b/src/IO/Stream/Slice/Reader.php new file mode 100644 index 0000000..5d64a23 --- /dev/null +++ b/src/IO/Stream/Slice/Reader.php @@ -0,0 +1,427 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Slice; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Seekable, Positionable +}; +use FireHub\Core\Type\IO\SeekOrigin; +use FireHub\Core\Foundation\Constant\Numeric\IntegerLimits; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Sliced Stream Reader + * + * Provides a seekable, read-only view over a fixed byte range of an underlying readable and seekable stream. + * + * Maintains an independent logical position within the slice. + * + * Reading repositions the underlying stream to the corresponding absolute offset. + * + * The underlying stream is borrowed and is not automatically closed. + * + * This implementation is intended for blocking streams. + * @since 1.0.0 + */ +final class Reader implements Readable, Seekable, Positionable { + + /** + * ### Current logical position + * @since 1.0.0 + * + * @var non-negative-int + */ + private int $position = 0; + + /** + * ### Closed state + * @since 1.0.0 + */ + private bool $closed = false; + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the underlying stream is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Seekable::isSeekable() To check if the underlying stream is seekable. + * @uses \FireHub\Core\Foundation\Constant\Numeric\IntegerLimits::MAX To check if the slice range exceeds the + * supported integer range. + * + * @param \FireHub\Core\Boundary\IO\Stream\Readable&\FireHub\Core\Boundary\IO\Stream\Seekable $stream+ * Underlying readable and seekable stream. + *
+ * @param non-negative-int $offset+ * Absolute starting byte offset. + *
+ * @param non-negative-int $length+ * Maximum number of bytes exposed by the slice. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the range is invalid or the underlying + * stream does not support reading and seeking. + * + * @return void + */ + public function __construct ( + private readonly Readable&Seekable $stream, + private readonly int $offset, + private readonly int $length + ) { + + if ($offset < 0 || $length < 0) + throw new StreamException( + 'Slice offset and length cannot be negative.' + ); + + if ($offset > IntegerLimits::MAX - $length) + throw new StreamException( + 'Slice range exceeds the supported integer range.' + ); + + if ( + $stream->isClosed() + || !$stream->isReadable() + || !$stream->isSeekable() + ) throw new StreamException( + 'The underlying stream must be open, readable, and seekable.' + ); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isClosed() To check if the underlying stream is closed. + */ + public function isClosed ():bool { + + return $this->closed || $this->stream->isClosed(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::isClosed() To check if the reader is closed. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::isReadable() To check if the underlying stream is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Seekable::isSeekable() To check if the underlying stream is seekable. + */ + public function isReadable ():bool { + + return !$this->isClosed() + && $this->stream->isReadable() + && $this->stream->isSeekable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::isClosed() To check if the reader is closed. + * @uses \FireHub\Core\Boundary\IO\Stream\Seekable::isSeekable() To check if the underlying stream is seekable. + */ + public function isSeekable ():bool { + + return !$this->isClosed() && $this->stream->isSeekable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::requireOpen() To ensure the reader is open. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function size ():int { + + $this->requireOpen(); + + return $this->length; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::requireReadable() To ensure the reader is readable. + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::eof() To check if the slice is at EOF. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read from the underlying stream. + * @uses \FireHub\Runtime\Math::min() To clamp the requested length. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To count the received bytes. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails or the requested length is + * invalid. + */ + public function read (int $length):string { + + $this->requireReadable(); + + if ($length < 0) + throw new StreamException( + 'Read length cannot be negative.' + ); + + if ($length === 0 || $this->eof()) return ''; + + $requested = Runtime\Math::min( + $length, + $this->remaining() + ); + + $this->stream->seek( + $this->offset + $this->position + ); + + $data = $this->stream->read($requested); + + $received = Runtime\Str\SB\Inspection::length($data); + + if ($received > $requested) + throw new StreamException( + 'The underlying stream returned more bytes than requested.' + ); + + if ($data === '' && !$this->stream->eof()) + throw new StreamException( + 'The underlying stream returned no data before reaching EOF.' + ); + + $this->position += $received; + + return $data; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::requireReadable() To ensure the reader is readable. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::eof() To check if the slice is at EOF. + * @uses \FireHub\Core\Boundary\IO\Stream\Readable::read() To read from the underlying stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + $this->requireReadable(); + + $contents = ''; + + while (!$this->eof()) { + + $chunk = $this->read(8192); + + if ($chunk === '') break; + + $contents .= $chunk; + + } + + return $contents; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::requireOpen() To ensure the reader is open. + * + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function eof ():bool { + + $this->requireOpen(); + + return $this->position >= $this->length; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::requireOpen() To ensure the reader is open. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + */ + public function tell ():int { + + $this->requireOpen(); + + return $this->position; + + } + + /** + * ### Moves the current position within the slice + * + * Changes the logical position relative to the beginning, current position, or end of the slice. + * + * The underlying stream position is not modified until the next read. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::requireOpen() To ensure the reader is open. + * @uses \FireHub\Core\Foundation\Constant\Numeric\IntegerLimits::MAX To check if the resulting position exceeds + * + * @param int $offset+ * Position offset in bytes. + *
+ * @param \FireHub\Core\Type\IO\SeekOrigin $origin [optional]+ * Reference position used to calculate the new position. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed, the resulting + * position exceeds the supported integer range, or the position is outside the slice boundaries. + * + * @return void + */ + public function seek (int $offset, SeekOrigin $origin = SeekOrigin::START):void { + + $this->requireOpen(); + + $base = match ($origin) { + + SeekOrigin::START => 0, + SeekOrigin::CURRENT => $this->position, + SeekOrigin::END => $this->length + + }; + + if ($offset > 0 && $base > IntegerLimits::MAX - $offset) + throw new StreamException( + 'Slice seek position exceeds the supported integer range.' + ); + + if ($offset < -$base || $offset > $this->length - $base) + throw new StreamException( + 'Cannot seek outside the slice boundaries.' + ); + + $this->position = $base + $offset; // @phpstan-ignore assign.propertyType + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::seek() To move the position to the beginning of the slice. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function rewind ():void { + + $this->seek(0); + + } + + /** + * ### Gets the slice starting offset + * @since 1.0.0 + * + * @return non-negative-int Absolute starting byte offset. + */ + public function offset ():int { + + return $this->offset; + + } + + /** + * ### Gets the number of remaining bytes + * @since 1.0.0 + * + * @return non-negative-int Remaining bytes within the slice. + */ + public function remaining ():int { + + /** @var non-negative-int */ + return $this->length - $this->position; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Requires an open reader + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::isClosed() To check if the reader is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the reader is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The sliced reader is closed.' + ); + + } + + /** + * ### Requires a readable stream + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::requireOpen() To check if the reader is open. + * @uses \FireHub\Foundation\IO\Stream\Slice\Reader::isReadable() To check if the underlying stream is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the underlying stream is not readable or + * seekable. + * + * @return void + */ + private function requireReadable ():void { + + $this->requireOpen(); + + if (!$this->isReadable()) + throw new StreamException( + 'The sliced reader is not readable.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Source/Byte.php b/src/IO/Stream/Source/Byte.php new file mode 100644 index 0000000..bc248f1 --- /dev/null +++ b/src/IO/Stream/Source/Byte.php @@ -0,0 +1,92 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.5 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream\Source; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\DataStructure\Stream\Source; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Byte Stream Source + * + * Adapts a readable I/O stream into a lazy sequence of individual bytes. + * + * Each element is a binary string containing exactly one byte. + * + * This source does not perform character encoding or Unicode decoding. + * + * Iteration consumes the stream from its current position without automatically rewinding or closing it. + * @since 1.0.0 + * + * @implements \FireHub\Foundation\DataStructure\Stream\Source+ * Source stream. + *
+ * @param positive-int $chunk_size [optional]+ * Number of bytes read per operation. + * + * Defaults to 8192. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the chunk size is invalid. + * + * @return void + */ + public function __construct ( + private Readable $stream, + private int $chunk_size = 8192 + ) { + + if ($chunk_size <= 0) + throw new StreamException( + 'Chunk size must be greater than zero.' + ); + + } + + /** + * ### Iterates over individual bytes + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Source\Chunk::iterate() To iterate over chunks. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of a string. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream cannot make progress before EOF. + * + * @return iterable+ * The readable stream used as the source of bytes. + *
+ * @param positive-int $size [optional]+ * Maximum number of bytes per chunk. + * + * Defaults to 8192. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the chunk size is not positive. + * + * @return void + */ + public function __construct ( + private Readable $stream, + private int $size = 8192 + ) { + + if ($size <= 0) + throw new StreamException( + 'Chunk size must be greater than zero.' + ); + + } + + /** + * ### Iterates over byte chunks + * + * Reads data lazily from the current stream position. + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Readable::read() To read data from the stream. + * @uses \FireHub\Foundation\IO\Stream\Readable::eof() To check if the stream has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream cannot make progress before EOF. + * + * @return iterable+ * Source stream. + *
+ * @param positive-int $chunk_size [optional]+ * Maximum bytes read per operation. + * + * Defaults to 8192. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the chunk size is invalid. + * + * @return void + */ + public function __construct ( + private Readable $stream, + private int $chunk_size = 8192 + ) { + + if ($chunk_size <= 0) + throw new StreamException( + 'Chunk size must be greater than zero.' + ); + + } + + /** + * ### Iterates over lines + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::read() To read from the stream. + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::eof() To check if the stream is at EOF. + * @uses \FireHub\Runtime\Str\SB\Search::firstPosition() To find the first occurrence of a substring. + * @uses \FireHub\Runtime\Str\SB\Access::part() To extract a substring. + * @uses \FireHub\Runtime\Str\SB\Search::endsWith() To check if a string ends with a specific substring. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream returns no data before EOF. + * + * @return iterable+ * First destination stream. + *
+ * @param Writable ...$others+ * Additional destination streams. + *
+ * + * @throws StreamException If a destination is not writable or the same destination instance is provided more + * than once. + * + * @return void + */ + public function __construct (Writable $first, Writable ...$others) { + + $streams = [$first, ...$others]; + + $seen = []; + + foreach ($streams as $stream) { + + if ($stream->isClosed() || !$stream->isWritable()) + throw new StreamException( + 'All tee destinations must be open and writable.' + ); + + $id = Runtime\ObjectModel\Identity::id($stream); + + if (isset($seen[$id])) + throw new StreamException( + 'The same destination cannot be registered more than once.' + ); + + $seen[$id] = true; + + } + + $this->streams = Runtime\Arr\Access::values($streams); // @phpstan-ignore assign.propertyType + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::isClosed() To check if the writer is closed. + */ + public function isClosed ():bool { + + if ($this->closed) return true; + + foreach ($this->streams as $stream) + if ($stream->isClosed()) return true; + + return false; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + *. + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::isClosed() To check if the writer is closed. + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::isWritable() To check if any destination is writable. + */ + public function isWritable ():bool { + + if ($this->failed || $this->isClosed()) + return false; + + foreach ($this->streams as $stream) + if (!$stream->isWritable()) return false; + + return true; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::requireOpen() To check if the writer is open. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + */ + public function size ():?int { + + $this->requireOpen(); + + return null; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::requireWritable() To check if the writer is writable. + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::writeAll() To write the input to all destinations. + * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the length of the input data. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If any destination cannot accept the complete + * input. + */ + public function write (string $data):int { + + $this->requireWritable(); + + $length = Runtime\Str\SB\Inspection::length($data); + + if ($length === 0) return 0; + + try { + + foreach ($this->streams as $stream) + $this->writeAll($stream, $data, $length); + + } catch (Throwable $exception) { + + $this->failed = true; + + throw new StreamException( + 'Tee write failed. Destinations may contain different amounts of data.', + previous: $exception + ); + + } + + $this->written += $length; + + return $length; + + } + + /** + * ### Gets successfully broadcast bytes + * + * Counts bytes from operations completed by every destination. Failed operations are not included. + * @since 1.0.0 + * + * @return non-negative-int Number of successfully broadcast bytes. + */ + public function written ():int { + + return $this->written; + + } + + /** + * ### Checks whether the writer has failed + * @since 1.0.0 + * + * @return bool True if a previous write failed. + */ + public function isFailed ():bool { + + return $this->failed; + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + public function close ():void { + + $this->closed = true; + + } + + /** + * ### Writes all bytes to one destination + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Writable::write() To write to the destination. + * @uses \FireHub\Runtime\Str\SB\Access::part() To get a part of the input data. + * + * @param \FireHub\Core\Boundary\IO\Stream\Writable $stream+ * Destination stream. + *
+ * + * @param string $data+ * Input data. + *
+ * + * @param positive-int $length+ * Input length. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the destination stops accepting data or + * reports an invalid write length. + * + * @return void + */ + private function writeAll (Writable $stream, string $data, int $length):void { + + $offset = 0; + + while ($offset < $length) { + + $remaining = Runtime\Str\SB\Access::part( + $data, + $offset + ); + + $written = $stream->write($remaining); + + $remaining_length = $length - $offset; + + if ($written <= 0 || $written > $remaining_length) + throw new StreamException( + 'The destination could not accept the remaining data.' + ); + + $offset += $written; + + } + + } + + /** + * ### Requires an open writer + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::isClosed() To check if the writer is closed. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer is closed. + * + * @return void + */ + private function requireOpen ():void { + + if ($this->isClosed()) + throw new StreamException( + 'The tee writer is closed.' + ); + + } + + /** + * ### Requires a writable state + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\Tee\Writer::isWritable() To check if any destination is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the writer has failed or any destination is + * unavailable. + * + * @return void + */ + private function requireWritable ():void { + + $this->requireOpen(); + + if ($this->failed) + throw new StreamException( + 'The tee writer is in a failed state.' + ); + + if (!$this->isWritable()) + throw new StreamException( + 'One or more tee destinations are not writable.' + ); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Temporary.php b/src/IO/Stream/Temporary.php new file mode 100644 index 0000000..367d49f --- /dev/null +++ b/src/IO/Stream/Temporary.php @@ -0,0 +1,223 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Positionable, Readable, Seekable, Writable +}; +use FireHub\Core\Type\IO\SeekOrigin; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime; + +/** + * ### Temporary Stream + * + * Provides a readable, writable, and seekable stream backed by PHP's php://temp stream wrapper. + * + * Stream contents are initially stored in memory. When the configured memory threshold is exceeded, PHP automatically + * moves the contents to a temporary file on disk. + * + * Unlike php://memory, this stream can handle large amounts of data without keeping the entire contents in memory. + * @since 1.0.0 + */ +final class Temporary extends ResourceStream implements Positionable, Seekable, Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the php://temp stream. + * + * @param non-negative-int $memory_threshold [optional]+ * Maximum number of bytes stored in memory before switching to temporary file storage. + * + * Defaults to 2 MiB (2,097,152 bytes). + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the memory threshold is invalid or the stream cannot be opened. + * + * @return void + */ + public function __construct (int $memory_threshold = 2097152) { + + if ($memory_threshold < 0) + throw new StreamException( + 'Maximum memory threshold cannot be negative.' + ); + + $resource = Runtime\Stream\Handle::open( + "php://temp/maxmemory:$memory_threshold", + Runtime\Stream\Enum\OpenMode::READ_WRITE_BINARY + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open temporary stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsSeekable() To check if the resource is seekable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isSeekable ():bool { + + return $this->resourceIsSeekable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::tellResource() To get the current position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the position cannot be determined. + */ + public function tell ():int { + + return $this->tellResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::seekResource() To seek to a specific position in the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function seek (int $offset, SeekOrigin $origin = SeekOrigin::START):void { + + $this->seekResource($offset, $origin); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::rewindResource() To rewind the resource to the beginning. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If seeking fails. + */ + public function rewind ():void { + + $this->rewindResource(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource is at the end of the stream. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Zip.php b/src/IO/Stream/Zip.php new file mode 100644 index 0000000..87e0c78 --- /dev/null +++ b/src/IO/Stream/Zip.php @@ -0,0 +1,153 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\Readable; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Stream\Enum\OpenMode; +use FireHub\Runtime; + +/** + * ### ZIP Archive Entry Stream + * + * Provides a readable stream backed by PHP's zip:// stream wrapper. + * + * Allows reading individual files stored inside ZIP archives without extracting the entire archive. + * + * The stream is read-only and does not guarantee seeking or positioning capabilities. + * + * Creating, modifying, and deleting ZIP archive entries are not supported by this abstraction. + * + * Requires the PHP zip extension. + * @since 1.0.0 + */ +final class Zip extends ResourceStream implements Readable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the ZIP archive entry. + * @uses \FireHub\Runtime\System\Extension::hasExtension() To validate the extension availability. + * @uses \FireHub\Runtime\Str\SB\Search::contains() To validate the entry path. + * + * @param non-empty-string $archive+ * Path to the ZIP archive. + *
+ * @param non-empty-string $entry+ * Path to the file inside the ZIP archive. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the extension is unavailable, the archive + * or entry path is invalid, or the entry cannot be opened. + * + * @return void + */ + public function __construct (string $archive, string $entry) { + + if (!Runtime\System\Extension::hasExtension('zip')) + throw new StreamException( + 'The zip extension is required to open ZIP archive streams.' + ); + + if ($archive === '') + throw new StreamException( + 'The ZIP archive path cannot be empty.' + ); + + if ($entry === '') + throw new StreamException( + 'The ZIP archive entry path cannot be empty.' + ); + + if (Runtime\Str\SB\Search::contains('#', $archive)) + throw new StreamException( + 'The ZIP archive path cannot contain the entry separator (#).' + ); + + $resource = Runtime\Stream\Handle::open( + "zip://$archive#$entry", + OpenMode::READ_BINARY + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open ZIP archive entry stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check whether EOF has been reached. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/IO/Stream/Zlib.php b/src/IO/Stream/Zlib.php new file mode 100644 index 0000000..ad9a38c --- /dev/null +++ b/src/IO/Stream/Zlib.php @@ -0,0 +1,185 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Foundation + */ + +namespace FireHub\Foundation\IO\Stream; + +use FireHub\Core\Boundary\IO\Stream\ { + Readable, Writable +}; +use FireHub\Foundation\IO\Stream\Exception\StreamException; +use FireHub\Runtime\Stream\Enum\OpenMode; +use FireHub\Runtime; + +/** + * ### Zlib Stream + * + * Provides a readable and writable stream backed by PHP's compress.zlib:// stream wrapper. + * + * Allows reading and writing gzip-compressed files using transparent compression and decompression. + * + * Reading and writing availability depend on the selected opening mode. + * + * This abstraction does not guarantee seeking and positioning. + * + * Requires the PHP zlib extension. + * @since 1.0.0 + */ +final class Zlib extends ResourceStream implements Readable, Writable { + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Stream\Handle::open() To open the compressed stream. + * @uses \FireHub\Runtime\System\Extension::hasExtension() To validate the extension availability. + * + * @param non-empty-string $path+ * Path to the gzip-compressed file. + *
+ * @param \FireHub\Runtime\Stream\Enum\OpenMode $mode [optional]+ * Stream opening mode. + * + * Only READ_BINARY and WRITE_BINARY are supported. + * + * Defaults to READ_BINARY. + *
+ * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the extension is unavailable, the opening + * mode is unsupported, or the stream cannot be opened. + * + * @return void + */ + public function __construct (string $path, OpenMode $mode = OpenMode::READ_BINARY) { + + if (!Runtime\System\Extension::hasExtension('zlib')) + throw new StreamException( + 'The zlib extension is required to open compressed streams.' + ); + + if ($path === '') + throw new StreamException( + 'The compressed file path cannot be empty.' + ); + + if ( + $mode !== OpenMode::READ_BINARY + && $mode !== OpenMode::WRITE_BINARY + ) throw new StreamException( + 'Zlib streams support only READ_BINARY and WRITE_BINARY opening modes.' + ); + + $resource = Runtime\Stream\Handle::open( + "compress.zlib://$path", + $mode + ); + + if ($resource === false) + throw new StreamException( + 'Unable to open zlib stream.' + ); + + parent::__construct($resource, Ownership::OWNED); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsReadable() To check if the resource is readable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isReadable ():bool { + + return $this->resourceIsReadable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceIsWritable() To check if the resource is writable. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function isWritable ():bool { + + return $this->resourceIsWritable(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResource() To read from the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function read (int $length):string { + + return $this->readResource($length); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::readResourceContents() To read the remaining contents of the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If reading fails. + */ + public function contents ():string { + + return $this->readResourceContents(); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::writeResource() To write to the resource. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If writing fails. + */ + public function write (string $data):int { + + return $this->writeResource($data); + + } + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @uses \FireHub\Foundation\IO\Stream\ResourceStream::resourceEof() To check if the resource has reached EOF. + * + * @throws \FireHub\Foundation\IO\Stream\Exception\StreamException If the stream is closed. + */ + public function eof ():bool { + + return $this->resourceEof(); + + } + +} \ No newline at end of file diff --git a/src/Identifier/Exception/InvalidIdentifierValueException.php b/src/Identifier/Exception/InvalidIdentifierValueException.php index 387fd71..d0d0cd3 100644 --- a/src/Identifier/Exception/InvalidIdentifierValueException.php +++ b/src/Identifier/Exception/InvalidIdentifierValueException.php @@ -21,6 +21,11 @@ */ final class InvalidIdentifierValueException extends DomainException { + /** + * @inheritDoc + * + * @since 1.0.0 + */ protected const string DEFAULT_MESSAGE = 'Invalid identifier value.'; } \ No newline at end of file diff --git a/src/Str/Ascii.php b/src/Str/Ascii.php index cec2e40..4682d2a 100644 --- a/src/Str/Ascii.php +++ b/src/Str/Ascii.php @@ -16,6 +16,7 @@ use FireHub\Foundation\Str; use FireHub\Core\Type\Str\Encoding; use FireHub\Foundation\Str\Exception\InvalidAsciiException; +use FireHub\Runtime; /** * ### Represents an ASCII encoded string value object @@ -38,7 +39,7 @@ * @since 1.0.0 * * @uses \FireHub\Core\Type\ValueObject::guard() As a guard. - * @uses \FireHub\Foundation\Str\Ascii::pattern() To check valid ASCII pattern. + * @uses \FireHub\Runtime\Str\SB\Regex::match() To check valid ASCII pattern. * * @throws \FireHub\Foundation\Str\Exception\InvalidAsciiException If string is not valid ASCII or encoding is * not ASCII. @@ -55,7 +56,7 @@ public function __construct (string $value, Encoding $encoding = Encoding::ASCII ); $this->guard( - fn() => $this->pattern()->match()->is()->ascii() === true, + fn() => !Runtime\Str\SB\Regex::match('/[\x80-\xFF]/', $value), fn() => new InvalidAsciiException('String must be valid ASCII.') ); diff --git a/src/Str/Base.php b/src/Str/Base.php index 6920e55..f13b31e 100644 --- a/src/Str/Base.php +++ b/src/Str/Base.php @@ -13,14 +13,15 @@ namespace FireHub\Foundation\Str; +use FireHub\Core\Type\Str\Encoded; use FireHub\Core\Type\ { - Char as BaseChar, Str + Char\Encoded as BaseChar, Str }; use FireHub\Core\Type\Str\Encoding; use FireHub\Core\Meta\Enum\Side; -use FireHub\Foundation\StringValue; -use FireHub\Foundation\Char; use FireHub\Core\Foundation\Constant\Numeric\IntegerLimits; +use FireHub\Foundation\EncodedStringValue; +use FireHub\Foundation\Char; use FireHub\Foundation\Str\Operation\ { Escape, Extract, Sanitize }; @@ -37,19 +38,19 @@ * * @template TValue of string * - * @extends \FireHub\Core\Type\Str
+ * use FireHub\Foundation\Str;
+ *
+ * $string = Str::of('The FireHub Project')->bytes();
+ *
+ * // 19
+ *
+ *
+ * @since 1.0.0
+ *
+ * @uses \FireHub\Runtime\Str\SB\Inspection::length() To get the string length.
+ *
+ * @return non-negative-int The number of bytes.
+ */
+ public function bytes ():int {
+
+ return Runtime\Str\SB\Inspection::length($this->value);
+
+ }
+
/**
* ### Finds the first occurrence of a substring in the string
*
@@ -405,6 +429,8 @@ public function lastIndexOf (string $find):int|false {
*
* @since 1.0.0
*
+ * @uses \FireHub\Foundation\Str\Base::split() To split the string into an array of characters.
+ *
* @throws \FireHub\Runtime\Exception\StringSplitLengthException If the $length parameter is less than 1.
* @throws \FireHub\Foundation\Char\Exception\InvalidLengthException If the string length is not 1.
* @throws \FireHub\Core\Exception\FireHubException If the condition is not met.
@@ -473,7 +499,7 @@ public function split (int $length = 1):array {
*
* @throws \FireHub\Runtime\Exception\StringSplitLengthException If the $length parameter is less than 1.
*
- * @return list* The string to surround the current string with. *
@@ -989,6 +1018,10 @@ public function duplicate (int $times, string $separator = ''):self { * * @since 1.0.0 * + * @uses \FireHub\Foundation\Str\Base::split() To split the string into an array of characters. + * @uses \FireHub\Runtime\Str\SB\Delimiter::implode() To reverse the string. + * @uses \FireHub\Runtime\Arr\Transform::reverse() To reverse the string. + * * @throws \FireHub\Runtime\Exception\StringSplitLengthException If the $length parameter is less than 1. * * @return static* Side to trim string. *
@@ -1352,7 +1387,7 @@ public function shuffle ():static { * @uses \FireHub\Runtime\Str\SB\Transform::repeat() To repeat the string. * @uses \FireHub\Foundation\Char::value() To get the character value. * - * @param \FireHub\Core\Type\Char
+ * @param \FireHub\Core\Type\Char\Encoded
* The character to use for masking.
*
+ * The raw binary string.
+ *
+ * The values to check.
+ *
+ * The value to check for.
+ *
+ * The values to check.
+ *
+ * The value to check for.
+ *
+ * The values to check for.
+ *
+ * A string to find position.
+ *
+ * A string to find position.
+ *
+ * The length of each character.
+ *
+ * The number of groups to split the string into.
+ *
+ * The boundary string.
+ *
+ * If the limit is set and positive, the returned array will contain a maximum of limit elements with the last
+ * element containing the rest of the string.
+ *
+ * If the limit parameter is negative, all components except the last – limit are returned.
+ *
+ * If the limit parameter is zero, then this is treated as 1.
+ *
+ * The string to prepend.
+ *
+ * The string to prepend.
+ *
+ * The string to prepend.
+ *
+ * The string to append.
+ *
+ * The string to surround the current string with.
+ *
+ * The number of times to repeat the string.
+ *
+ * The separator to use between repeated strings.
+ *
+ * The number of times to duplicate the string.
+ *
+ * The separator to use between duplicate strings.
+ *
+ * If the value of $length is negative, less than, or equal to the length of the input string, no padding takes
+ * place.
+ *
+ * The pad may be truncated if the required number of padding characters can't be evenly divided by the pad's
+ * length.
+ *
+ * Pad side.
+ *
+ * Side to trim string.
+ *
+ * The stripped characters can also be specified using the char-list parameter.
+ *
+ * List all characters that you want to be stripped. With '..', you can specify a range of characters.
+ *
+ * @param \FireHub\Core\Type\Str\Encoded
* The string to convert.
*