class-basebytereadstream.php
2 weeks ago
class-deflatereadstream.php
2 weeks ago
class-filereadstream.php
2 weeks ago
class-inflatereadstream.php
2 weeks ago
class-limitedbytereadstream.php
2 weeks ago
class-transformedreadstream.php
2 weeks ago
interface-bytereadstream.php
2 weeks ago
class-limitedbytereadstream.php
44 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WordPress\ByteStream\ReadStream; |
| 4 | |
| 5 | /** |
| 6 | * A reader that limits the number of bytes that can be read. |
| 7 | */ |
| 8 | class LimitedByteReadStream extends BaseByteReadStream { |
| 9 | private $upstream; |
| 10 | private $limit; |
| 11 | private $initial_offset; |
| 12 | |
| 13 | public function __construct( ByteReadStream $upstream, int $limit ) { |
| 14 | $this->upstream = $upstream; |
| 15 | $this->limit = $limit; |
| 16 | $this->initial_offset = $upstream->tell(); |
| 17 | } |
| 18 | |
| 19 | protected function internal_pull( $max_bytes ): string { |
| 20 | $max_bytes = min( |
| 21 | $max_bytes, |
| 22 | $this->limit - $this->tell() |
| 23 | ); |
| 24 | if ( $max_bytes <= 0 ) { |
| 25 | return ''; |
| 26 | } |
| 27 | $this->upstream->pull( $max_bytes ); |
| 28 | |
| 29 | return $this->upstream->consume( $max_bytes ); |
| 30 | } |
| 31 | |
| 32 | public function length(): ?int { |
| 33 | return $this->limit; |
| 34 | } |
| 35 | |
| 36 | protected function internal_reached_end_of_data(): bool { |
| 37 | return $this->tell() >= $this->limit || $this->upstream->reached_end_of_data(); |
| 38 | } |
| 39 | |
| 40 | protected function seek_outside_of_buffer( int $target_offset ): void { |
| 41 | $this->upstream->seek( $this->initial_offset + $target_offset ); |
| 42 | } |
| 43 | } |
| 44 |