PluginProbe
ManageWP Worker / 4.9.29
ManageWP Worker v4.9.29
4.9.38 4.9.37 4.9.36 4.9.35 4.9.34 3.8.7 3.8.8 3.9.0 3.9.1 3.9.10 3.9.11 3.9.12 3.9.13 3.9.14 3.9.15 3.9.16 3.9.17 3.9.18 3.9.19 3.9.2 3.9.20 3.9.21 3.9.22 3.9.23 3.9.24 All 73 releases
worker / src / MWP / Stream / Base64EncodedStream.php

Base64EncodedStream.php in ManageWP Worker 4.9.29, at src/MWP/Stream/Base64EncodedStream.php

57 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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