Passed
Push — master ( beaa4b...da3f2a )
by Shahrad
02:02
created

startTicker()   A

Complexity

Conditions 5
Paths 19

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
nc 19
nop 2
dl 0
loc 29
c 1
b 0
f 0
cc 5
rs 9.3888
1
<?php
2
require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';
3
4
use EasyHttp\Utils\WSConfig;
5
use EasyHttp\WebSocket;
6
7
error_reporting(E_ALL);
8
ini_set('display_errors', 1);
9
10
/**
11
 * @param array $ids
12
 * @param callable $callback
13
 */
14
function startTicker(array $ids, callable $callback): void
15
{
16
	try {
17
18
		$close_time = time() + 10;
19
		$ClientConfig = (new WSConfig())->setFragmentSize(8096)->setTimeout(15);
20
		$WebSocketClient = new WebSocket('wss://stream.coinmarketcap.com/price/latest', $ClientConfig);
21
22
		$WebSocketClient->send(json_encode([
23
			'method' => 'subscribe',
24
			'id' => 'price',
25
			'data' => [
26
				'cryptoIds' => $ids,
27
				'index' => 'detail'
28
			]
29
		]));
30
31
		while ($close_time > time()) {
32
			if (($message = $WebSocketClient->receive()) != "") {
33
				$json_response = json_decode($message, true);
34
35
				if ($json_response['id'] == "price") {
36
					$callback($json_response);
37
				}
38
			}
39
		}
40
41
	} catch (Exception $e) {
42
		echo "<b>Error</b>: " . $e->getMessage();
43
	}
44
}
45
46
echo "<pre>Start Tome: " . date('Y-m-d H:i:s') . "</pre><br/>";
47
48
$responses = [];
49
startTicker([1, 1027, 825, 3408, 1839, 4687, 52, 2010, 5426], function ($data) use (&$responses) {
50
	$responses[] = $data;
51
});
52
53
echo "<pre>" . json_encode($responses, JSON_PRETTY_PRINT) . "</pre><br/>";
54
echo "<pre>End Time: " . date('Y-m-d H:i:s') . "</pre>";