-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathEventSource.php
More file actions
76 lines (62 loc) · 1.82 KB
/
EventSource.php
File metadata and controls
76 lines (62 loc) · 1.82 KB
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
69
70
71
72
73
74
75
76
<?php
namespace Casper\EventStream;
class EventSource
{
public const EVENT_TYPE_MAIN = 'main';
public const EVENT_TYPE_DEPLOYS = 'deploys';
public const EVENT_TYPE_SIGS = 'sigs';
private string $url;
private $onMessage;
private bool $aborted = false;
public function __construct(string $url)
{
$this->url = $url;
}
public function onMessage(callable $callback): void
{
$this->onMessage = $callback;
}
public function abort()
{
$this->aborted = true;
}
/**
* @throws \Exception
*/
public function connect(string $eventsType, int $startFrom = 0): void
{
$this->assertEventTypeIsValid($eventsType);
$curl = curl_init($this->url . '/events/' . $eventsType);
curl_setopt_array($curl, array(
CURLOPT_WRITEFUNCTION => function ($_, $data) {
try {
$event = new Event(trim($data));
if (is_callable($this->onMessage)) {
($this->onMessage)($event);
}
} catch (\Exception $_) {
}
return strlen($data);
},
CURLOPT_NOPROGRESS => false,
CURLOPT_PROGRESSFUNCTION => function () {
return $this->aborted;
}
));
curl_exec($curl);
$error = curl_error($curl);
if (!$this->aborted && $error) {
throw new \Exception($error);
}
curl_close($curl);
}
/**
* @throws \Exception
*/
private function assertEventTypeIsValid(string $eventType): void
{
if (!in_array($eventType, [self::EVENT_TYPE_MAIN, self::EVENT_TYPE_DEPLOYS, self::EVENT_TYPE_SIGS])) {
throw new \Exception('Invalid event type');
}
}
}