1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace WyriHaximus\React\Stream\Base64; |
4
|
|
|
|
5
|
|
|
use Evenement\EventEmitter; |
6
|
|
|
use React\Stream\ReadableStreamInterface; |
7
|
|
|
use React\Stream\Util; |
8
|
|
|
use React\Stream\WritableStreamInterface; |
9
|
|
|
|
10
|
|
View Code Duplication |
final class ReadableStreamBase64Decode extends EventEmitter implements ReadableStreamInterface |
|
|
|
|
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var WritableStreamInterface |
14
|
|
|
*/ |
15
|
|
|
private $stream; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
private $buffer = ''; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param ReadableStreamInterface $stream |
24
|
|
|
*/ |
25
|
|
|
public function __construct(ReadableStreamInterface $stream) |
26
|
|
|
{ |
27
|
|
|
$this->stream = $stream; |
|
|
|
|
28
|
|
|
$this->stream->on('data', function ($data) { |
29
|
|
|
$this->buffer .= $data; |
30
|
|
|
$this->emit('data', [$this->processBuffer()]); |
31
|
|
|
}); |
32
|
|
|
$this->stream->once('close', function () { |
33
|
|
|
$this->emit('data', [base64_decode($this->buffer, true)]); |
34
|
|
|
$this->emit('close'); |
35
|
|
|
}); |
36
|
|
|
Util::forwardEvents($stream, $this, ['error', 'end']); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function isReadable() |
40
|
|
|
{ |
41
|
|
|
return $this->stream->isReadable(); |
|
|
|
|
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function pause() |
45
|
|
|
{ |
46
|
|
|
return $this->stream->pause(); |
|
|
|
|
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function resume() |
50
|
|
|
{ |
51
|
|
|
return $this->stream->resume(); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function pipe(WritableStreamInterface $dest, array $options = []) |
55
|
|
|
{ |
56
|
|
|
return $this->stream->pipe($dest, $options); |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function close() |
60
|
|
|
{ |
61
|
|
|
$this->stream->close(); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
private function processBuffer(): string |
65
|
|
|
{ |
66
|
|
|
$length = strlen($this->buffer); |
67
|
|
|
$buffer = base64_decode(substr($this->buffer, 0, $length - $length % 4), true); |
68
|
|
|
$this->buffer = substr($this->buffer, $length - $length % 4); |
69
|
|
|
|
70
|
|
|
return $buffer; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.