-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSseClient.php
68 lines (63 loc) · 1.74 KB
/
SseClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
require 'vendor/autoload.php';
class SseClient
{
const END_OF_MESSAGE = "/\r\n\r\n|\n\n|\r\r/";
/** @var GuzzleHttp\Client */
private $client;
/** @var GuzzleHttp\Psr7\Response */
private $response;
public function __construct()
{
$this->client = new GuzzleHttp\Client([
'headers' => [
'Cache-Control' => 'no-cache',
],
]);
}
public function request($method, $url, $headers, $body)
{
if (!$method) {
$method = 'GET';
}
if (!$headers) {
$headers = [];
}
if (!array_key_exists('Content-Type', $headers)) {
$headers['Content-Type'] = 'application/json';
}
$this->response = $this->client->request($method, $url, [
'verify' => false,
'stream' => true,
'headers' => $headers,
'body' => $body
]);
return $this->response;
}
public function eventStream()
{
$buffer = '';
$body = $this->response->getBody();
try {
while (true) {
if ($body->eof()) {
break;
}
$buffer .= $body->read(1);
if (preg_match(self::END_OF_MESSAGE, $buffer)) {
$parts = preg_split(self::END_OF_MESSAGE, $buffer, 2);
$rawMessage = $parts[0];
$remaining = $parts[1];
$buffer = $remaining;
$event = Event::parse($rawMessage);
yield $event;
}
}
} finally {
try {
$body->close();
} catch (Exception $e) {
}
}
}
}