1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace WyriHaximus\React\Stream\Hash; |
4
|
|
|
|
5
|
|
|
use Evenement\EventEmitter; |
6
|
|
|
use React\Stream\WritableStreamInterface; |
7
|
|
|
|
8
|
|
|
final class WritableStreamHash extends EventEmitter implements WritableStreamInterface |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var WritableStreamInterface |
12
|
|
|
*/ |
13
|
|
|
private $stream; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var resource |
17
|
|
|
*/ |
18
|
|
|
private $context; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* WritableStreamHash constructor. |
22
|
|
|
* @param WritableStreamInterface $stream |
23
|
|
|
* @param string $algo |
24
|
|
|
* @param string|null $key |
25
|
|
|
*/ |
26
|
368 |
|
public function __construct(WritableStreamInterface $stream, string $algo, string $key = null) |
27
|
|
|
{ |
28
|
368 |
|
$this->stream = $stream; |
29
|
368 |
|
$options = [$algo]; |
30
|
368 |
View Code Duplication |
if ($key !== null && strlen($key) > 0) { |
|
|
|
|
31
|
184 |
|
$options[] = HASH_HMAC; |
32
|
184 |
|
$options[] = $key; |
33
|
|
|
} |
34
|
368 |
|
$this->context = hash_init(...$options); |
35
|
368 |
View Code Duplication |
$this->stream->once('close', function () use ($algo) { |
|
|
|
|
36
|
368 |
|
$hash = hash_final($this->context, true); |
37
|
368 |
|
if (count($this->listeners('hash')) > 0) { |
38
|
368 |
|
$this->emit('hash', [ |
39
|
368 |
|
bin2hex($hash), |
40
|
368 |
|
$algo, |
41
|
|
|
]); |
42
|
|
|
} |
43
|
368 |
|
if (count($this->listeners('hash_raw')) > 0) { |
44
|
368 |
|
$this->emit('hash_raw', [ |
45
|
368 |
|
$hash, |
46
|
368 |
|
$algo, |
47
|
|
|
]); |
48
|
|
|
} |
49
|
368 |
|
}); |
50
|
368 |
|
} |
51
|
|
|
|
52
|
|
|
public function isWritable() |
53
|
|
|
{ |
54
|
|
|
return $this->stream->isWritable(); |
55
|
|
|
} |
56
|
|
|
|
57
|
368 |
|
public function write($data) |
58
|
|
|
{ |
59
|
368 |
|
hash_update($this->context, $data); |
60
|
|
|
|
61
|
368 |
|
return $this->stream->write($data); |
62
|
|
|
} |
63
|
|
|
|
64
|
368 |
|
public function end($data = null) |
65
|
|
|
{ |
66
|
368 |
|
if ($data !== null) { |
67
|
|
|
hash_update($this->context, $data); |
68
|
|
|
} |
69
|
368 |
|
$this->stream->end($data); |
70
|
368 |
|
} |
71
|
|
|
|
72
|
|
|
public function close() |
73
|
|
|
{ |
74
|
|
|
$this->stream->close(); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
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.