class-bytetransformer.php
2 weeks ago
class-checksumtransformer.php
2 weeks ago
class-deflatetransformer.php
2 weeks ago
class-inflatetransformer.php
2 weeks ago
class-inflatetransformer.php
49 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WordPress\ByteStream\ByteTransformer; |
| 4 | |
| 5 | use WordPress\ByteStream\ByteStreamException; |
| 6 | |
| 7 | /** |
| 8 | * A writer that inflates compressed bytes. |
| 9 | */ |
| 10 | class InflateTransformer implements ByteTransformer { |
| 11 | |
| 12 | private $inflate_handle; |
| 13 | |
| 14 | public function __construct( string $encoding = ZLIB_ENCODING_DEFLATE ) { |
| 15 | $this->inflate_handle = inflate_init( $encoding ); |
| 16 | if ( false === $this->inflate_handle ) { |
| 17 | throw new ByteStreamException( 'Failed to initialize inflate handle' ); |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | public function filter_bytes( string $bytes ) { |
| 22 | if ( null === $this->inflate_handle ) { |
| 23 | throw new ByteStreamException( 'Inflate handle is not initialized' ); |
| 24 | } |
| 25 | |
| 26 | $inflated_data = inflate_add( $this->inflate_handle, $bytes, ZLIB_NO_FLUSH ); |
| 27 | if ( false === $inflated_data ) { |
| 28 | $last_error = error_get_last(); |
| 29 | if ( empty( $last_error ) ) { |
| 30 | $last_error = array( 'message' => 'Unknown error' ); |
| 31 | } |
| 32 | throw new ByteStreamException( esc_html( 'Failed to inflate data: ' . $last_error['message'] ) ); |
| 33 | } |
| 34 | |
| 35 | return $inflated_data; |
| 36 | } |
| 37 | |
| 38 | public function flush(): string { |
| 39 | if ( null === $this->inflate_handle ) { |
| 40 | throw new ByteStreamException( 'closing the inflate filter?' ); |
| 41 | } |
| 42 | |
| 43 | $last_chunk = inflate_add( $this->inflate_handle, '', ZLIB_FINISH ); |
| 44 | $this->inflate_handle = null; |
| 45 | |
| 46 | return $last_chunk; |
| 47 | } |
| 48 | } |
| 49 |