1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Codenixsv\BitfinexWs; |
6
|
|
|
|
7
|
|
|
use Codenixsv\BitfinexWs\Handler\Fulfilled; |
8
|
|
|
use Codenixsv\BitfinexWs\Handler\Rejected; |
9
|
|
|
use Ratchet\RFC6455\Messaging\Message; |
10
|
|
|
use Ratchet\Client\Connector; |
11
|
|
|
use React\EventLoop\Factory; |
12
|
|
|
use React\EventLoop\LoopInterface; |
13
|
|
|
use React\Socket\Connector as ReactConnector; |
14
|
|
|
use React\Promise\PromiseInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class WsClient |
18
|
|
|
* @package Codenixsv\BitfinexWs |
19
|
|
|
*/ |
20
|
|
|
class WsClient implements BaseWsClient |
21
|
|
|
{ |
22
|
|
|
public const EVENT_MESSAGE = 'message'; |
23
|
|
|
public const EVENT_CLOSE = 'close'; |
24
|
|
|
public const EVENT_ERROR = 'error'; |
25
|
|
|
|
26
|
|
|
/** @var LoopInterface */ |
27
|
|
|
private $loop; |
28
|
|
|
|
29
|
|
|
/** @var Connector */ |
30
|
|
|
private $connector; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* WsClient constructor. |
34
|
|
|
* @param string $dns |
35
|
|
|
* @param int $timeout |
36
|
|
|
* @param LoopInterface|null $loop |
37
|
|
|
*/ |
38
|
3 |
|
public function __construct(string $dns = '8.8.8.8', int $timeout = 10, ?LoopInterface $loop = null) |
39
|
|
|
{ |
40
|
3 |
|
$this->loop = $loop ?: Factory::create(); |
41
|
3 |
|
$this->connector = $this->createConnector($this->loop, $dns, $timeout); |
42
|
3 |
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string $url |
46
|
|
|
* @param Message $message |
47
|
|
|
* @param array $events |
48
|
|
|
* @param callable $onRejected |
49
|
|
|
*/ |
50
|
1 |
|
public function connect(string $url, Message $message, array $events, callable $onRejected): void |
51
|
|
|
{ |
52
|
1 |
|
$promise = $this->connector($url); |
53
|
|
|
|
54
|
1 |
|
$onFulfilled = new Fulfilled($message, $events); |
55
|
1 |
|
$onRejected = new Rejected($this->loop, $onRejected); |
56
|
|
|
|
57
|
1 |
|
$promise->then($onFulfilled, $onRejected); |
58
|
|
|
|
59
|
1 |
|
$this->loop->run(); |
60
|
1 |
|
} |
61
|
|
|
|
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param $url |
65
|
|
|
* @return PromiseInterface |
66
|
|
|
*/ |
67
|
1 |
|
private function connector($url): PromiseInterface |
68
|
|
|
{ |
69
|
1 |
|
$connector = $this->connector; |
70
|
|
|
|
71
|
1 |
|
return $connector($url); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @param LoopInterface $loop |
76
|
|
|
* @param string $dns |
77
|
|
|
* @param int $timeout |
78
|
|
|
* @return Connector |
79
|
|
|
*/ |
80
|
3 |
|
private function createConnector(LoopInterface $loop, string $dns, int $timeout): Connector |
81
|
|
|
{ |
82
|
3 |
|
$reactConnector = new ReactConnector($loop, [ |
83
|
3 |
|
'dns' => $dns, |
84
|
3 |
|
'timeout' => $timeout |
85
|
|
|
]); |
86
|
|
|
|
87
|
3 |
|
return new Connector($loop, $reactConnector); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|