1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Thruster\Component\Stream; |
4
|
|
|
|
5
|
|
|
use Thruster\Component\EventEmitter\EventEmitterInterface; |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Trait UtilsTrait |
10
|
|
|
* |
11
|
|
|
* @package Thruster\Component\Stream |
12
|
|
|
* @author Aurimas Niekis <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
trait UtilsTrait |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @param ReadableStreamInterface $source |
18
|
|
|
* @param WritableStreamInterface $destination |
19
|
|
|
* @param array $options |
20
|
|
|
* |
21
|
|
|
* @return WritableStreamInterface |
22
|
|
|
*/ |
23
|
11 |
|
public function pipeAll(ReadableStreamInterface $source, WritableStreamInterface $destination, array $options = []) |
24
|
|
|
{ |
25
|
|
|
// TODO: use stream_copy_to_stream |
26
|
|
|
// it is 4x faster than this |
27
|
|
|
// but can lose data under load with no way to recover it |
28
|
11 |
|
$destination->emit('pipe', array($source)); |
29
|
|
|
|
30
|
|
|
$source->on('data', function ($data) use ($source, $destination) { |
31
|
8 |
|
$feedMore = $destination->write($data); |
32
|
8 |
|
if (false === $feedMore) { |
33
|
1 |
|
$source->pause(); |
34
|
|
|
} |
35
|
11 |
|
}); |
36
|
|
|
|
37
|
|
|
$destination->on('drain', function () use ($source) { |
38
|
1 |
|
$source->resume(); |
39
|
11 |
|
}); |
40
|
|
|
|
41
|
11 |
|
$end = isset($options['end']) ? $options['end'] : true; |
42
|
|
|
|
43
|
11 |
|
if ($end && $source !== $destination) { |
44
|
|
|
$source->on('end', function () use ($destination) { |
45
|
2 |
|
$destination->end(); |
46
|
11 |
|
}); |
47
|
|
|
} |
48
|
|
|
|
49
|
11 |
|
return $destination; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param EventEmitterInterface $source |
54
|
|
|
* @param EventEmitterInterface $target |
55
|
|
|
* @param array $events |
56
|
|
|
*/ |
57
|
22 |
|
public function forwardEvents(EventEmitterInterface $source, EventEmitterInterface $target, array $events) |
58
|
|
|
{ |
59
|
22 |
|
foreach ($events as $event) { |
60
|
22 |
|
$source->on($event, function () use ($event, $target) { |
61
|
11 |
|
$target->emit($event, func_get_args()); |
62
|
22 |
|
}); |
63
|
|
|
} |
64
|
22 |
|
} |
65
|
|
|
} |
66
|
|
|
|