| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <contact@managewp.com> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
class MWP_Stream_Base64EncodedStream extends MWP_Stream_Decorator |
| 12 |
{ |
| 13 |
|
| 14 |
/** @var MWP_Stream_Interface */ |
| 15 |
private $buffer; |
| 16 |
|
| 17 |
const BASE64_BLOCK_SIZE = 4; |
| 18 |
const ORIGIN_BLOCK_SIZE = 3; |
| 19 |
|
| 20 |
public function __construct(MWP_Stream_Interface $stream) |
| 21 |
{ |
| 22 |
parent::__construct($stream); |
| 23 |
$this->buffer = new MWP_Stream_Buffer(); |
| 24 |
} |
| 25 |
|
| 26 |
public function eof() |
| 27 |
{ |
| 28 |
return $this->buffer->eof() && $this->getStream()->eof(); |
| 29 |
} |
| 30 |
|
| 31 |
public function read($length) |
| 32 |
{ |
| 33 |
$readFromBuffer = $this->buffer->read($length); |
| 34 |
if (strlen($readFromBuffer) === $length) { |
| 35 |
return $readFromBuffer; |
| 36 |
} |
| 37 |
|
| 38 |
$remaining = $length - strlen($readFromBuffer); |
| 39 |
|
| 40 |
// Calculate the approximate length required to read so that the base64 encoded stream does not have padding. |
| 41 |
// base64 is calculated for blocks of 3 input characters resulting in 4 output characters. |
| 42 |
// strlen(base64_encode($str)) ==> strlen($str) * 4 / 3 |
| 43 |
// |
| 44 |
// This leads to: |
| 45 |
// |
| 46 |
// strlen($str) ==> strlen(base64_encode($str)) * 3 / 4 |
| 47 |
// |
| 48 |
// Meaning, to read $length characters from the base64 encoded string, read 3/4 of $length from the original stream. |
| 49 |
// $length is first rounded to the first larger number divisible by 4 since base64 encoded strings come in blocks of 4 characters. |
| 50 |
$closestGroupLength = $remaining + (self::BASE64_BLOCK_SIZE - $remaining % self::BASE64_BLOCK_SIZE); |
| 51 |
$read = $closestGroupLength * self::ORIGIN_BLOCK_SIZE / self::BASE64_BLOCK_SIZE; |
| 52 |
$this->buffer->write(base64_encode($this->getStream()->read($read))); |
| 53 |
|
| 54 |
return $readFromBuffer.$this->buffer->read($remaining); |
| 55 |
} |
| 56 |
} |
| 57 |
|