class-bytewritestream.php
6 days ago
class-filewritestream.php
6 days ago
class-transformedwritestream.php
6 days ago
class-transformedwritestream.php
82 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WordPress\ByteStream\WriteStream; |
| 4 | |
| 5 | use ArrayAccess; |
| 6 | use ReturnTypeWillChange; |
| 7 | use WordPress\ByteStream\ByteStreamException; |
| 8 | use WordPress\ByteStream\ByteTransformer\ByteTransformer; |
| 9 | |
| 10 | class TransformedWriteStream implements ByteWriteStream, ArrayAccess { |
| 11 | |
| 12 | /** |
| 13 | * @var ByteWriteStream |
| 14 | */ |
| 15 | private $writer; |
| 16 | |
| 17 | /** |
| 18 | * @var ByteTransformer[] |
| 19 | */ |
| 20 | private $filters = array(); |
| 21 | |
| 22 | public function __construct( ByteWriteStream $writer, array $filters = array() ) { |
| 23 | $this->writer = $writer; |
| 24 | $this->filters = $filters; |
| 25 | } |
| 26 | |
| 27 | public function append_bytes( string $chunk ): void { |
| 28 | foreach ( $this->filters as $filter ) { |
| 29 | $chunk = $filter->filter_bytes( $chunk ); |
| 30 | if ( false === $chunk ) { |
| 31 | return; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | $this->writer->append_bytes( $chunk ); |
| 36 | } |
| 37 | |
| 38 | public function get_downstream_writer(): ByteWriteStream { |
| 39 | return $this->writer; |
| 40 | } |
| 41 | |
| 42 | public function close_writing(): void { |
| 43 | foreach ( $this->filters as $filter ) { |
| 44 | $this->writer->append_bytes( |
| 45 | $filter->flush() |
| 46 | ); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * |
| 52 | * @param string $offset The offset to get. |
| 53 | * @throws ByteStreamException If the filter is not found. |
| 54 | */ |
| 55 | #[ReturnTypeWillChange] |
| 56 | public function offsetGet( $offset ) { |
| 57 | if ( ! isset( $this->filters[ $offset ] ) ) { |
| 58 | throw new ByteStreamException( esc_html( sprintf( 'Filter %s not found', $offset ) ) ); |
| 59 | } |
| 60 | |
| 61 | return $this->filters[ $offset ]; |
| 62 | } |
| 63 | |
| 64 | /** @disregard P1038 */ |
| 65 | #[ReturnTypeWillChange] |
| 66 | public function offsetExists( $offset ) { |
| 67 | return isset( $this->filters[ $offset ] ); |
| 68 | } |
| 69 | |
| 70 | /** @disregard P1038 */ |
| 71 | #[ReturnTypeWillChange] |
| 72 | public function offsetSet( $offset, $value ) { |
| 73 | $this->filters[ $offset ] = $value; |
| 74 | } |
| 75 | |
| 76 | /** @disregard P1038 */ |
| 77 | #[ReturnTypeWillChange] |
| 78 | public function offsetUnset( $offset ) { |
| 79 | unset( $this->filters[ $offset ] ); |
| 80 | } |
| 81 | } |
| 82 |