|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thruster\Component\PacketHandler; |
|
4
|
|
|
|
|
5
|
|
|
use Thruster\Component\EventEmitter\EventEmitterInterface; |
|
6
|
|
|
use Thruster\Component\EventEmitter\EventEmitterTrait; |
|
7
|
|
|
use Thruster\Component\PacketHandler\Exception\InvalidPackageReceivedException; |
|
8
|
|
|
use Thruster\Component\Stream\Stream; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class StreamHandler |
|
12
|
|
|
* |
|
13
|
|
|
* @package Thruster\Component\PacketHandler |
|
14
|
|
|
* @author Aurimas Niekis <[email protected]> |
|
15
|
|
|
*/ |
|
16
|
|
|
class StreamHandler implements EventEmitterInterface |
|
17
|
|
|
{ |
|
18
|
|
|
use EventEmitterTrait; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var string |
|
22
|
|
|
*/ |
|
23
|
|
|
private $separator; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var Stream |
|
27
|
|
|
*/ |
|
28
|
|
|
private $stream; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var string |
|
32
|
|
|
*/ |
|
33
|
|
|
private $buffer; |
|
34
|
|
|
|
|
35
|
9 |
|
public function __construct(Stream $stream, string $separator = "\r\n\r\n") |
|
36
|
|
|
{ |
|
37
|
9 |
|
$this->buffer = ''; |
|
38
|
9 |
|
$this->stream = $stream; |
|
39
|
9 |
|
$this->separator = $separator; |
|
40
|
|
|
|
|
41
|
9 |
|
$this->stream->on('data', [$this, 'onData']); |
|
42
|
9 |
|
} |
|
43
|
|
|
|
|
44
|
1 |
|
public function send($data) |
|
|
|
|
|
|
45
|
|
|
{ |
|
46
|
1 |
|
$package = new Package(func_get_args()); |
|
47
|
|
|
|
|
48
|
1 |
|
$packageString = base64_encode(serialize($package)) . $this->separator; |
|
49
|
|
|
|
|
50
|
1 |
|
return $this->stream->write($packageString); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
3 |
|
public function onData($data) |
|
54
|
|
|
{ |
|
55
|
3 |
|
$this->buffer .= $data; |
|
56
|
|
|
|
|
57
|
3 |
|
if (preg_match('/' . $this->separator . '/', $this->buffer)) { |
|
58
|
3 |
|
$messages = explode($this->separator, $this->buffer); |
|
59
|
|
|
|
|
60
|
3 |
|
$this->buffer = array_pop($messages); |
|
61
|
|
|
|
|
62
|
3 |
|
foreach ($messages as $message) { |
|
63
|
|
|
/** @var Package $package */ |
|
64
|
3 |
|
$package = unserialize(base64_decode($message)); |
|
65
|
|
|
|
|
66
|
3 |
|
if ($package instanceof Package) { |
|
67
|
1 |
|
$package->setStream($this->stream); |
|
68
|
|
|
|
|
69
|
1 |
|
$this->emit('package', [$package]); |
|
70
|
|
|
} else { |
|
71
|
3 |
|
throw new InvalidPackageReceivedException($package); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
1 |
|
} |
|
76
|
|
|
|
|
77
|
|
|
/** |
|
78
|
|
|
* @return Stream |
|
79
|
|
|
*/ |
|
80
|
1 |
|
public function getStream() |
|
81
|
|
|
{ |
|
82
|
1 |
|
return $this->stream; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.