-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.php
81 lines (69 loc) · 1.98 KB
/
Client.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
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/*
* (c) Jérémy Marodon <[email protected]>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Th3Mouk\EventStoreClient;
use GuzzleHttp\RequestOptions;
class Client
{
private $dsn;
private $http;
public function __construct($dsn)
{
$this->dsn = $dsn;
$this->http = new \GuzzleHttp\Client();
}
/**
* Metadata are not available with this method
*/
public function sendEvent(string $stream, Event $event)
{
$this->http->post(
$this->getUrl($stream),
[
RequestOptions::HEADERS => [
Headers::EVENT_ID => $event->getId(),
Headers::EVENT_TYPE => $event->getType(),
],
RequestOptions::JSON => $event->getData(),
]
);
}
public function sendCollection(string $stream, EventCollection $collection)
{
$this->http->post(
$this->getUrl($stream),
[
RequestOptions::HEADERS => [
'Content-type' => 'application/vnd.eventstore.events+json',
],
RequestOptions::BODY => json_encode($collection->toArray()),
]
);
}
/**
* @param bool $wrap This option automatically wrap an unique Event into an
* EventCollection which allows metadata
*/
public function send(string $stream, $payload, $wrap = true)
{
if (is_a($payload, 'EventCollection')) {
$this->sendCollection($stream, $payload);
return;
}
if ($wrap) {
$this->sendCollection(
$stream,
(new EventCollection())->add($payload)
);
return;
}
$this->sendEvent($stream, $payload);
}
private function getUrl(string $stream)
{
return $this->dsn.'/streams/'.$stream;
}
}