Skip to content

Commit 2c3b130

Browse files
committed
feat(ap-1505): implemenet the basic EvolvClient functionality
1 parent 02aacf1 commit 2c3b130

33 files changed

+4455
-0
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/node_modules
2+
/vendor
3+
/.idea
4+
/php.ini
5+
.env
6+
.phpunit.result.cache

App/Beacon.php

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace App;
6+
7+
use App\EvolvContext;
8+
9+
require __DIR__ . '/../vendor/autoload.php';
10+
require_once __DIR__ . '/EvolvStore.php';
11+
require_once __DIR__ . '/Beacon.php';
12+
13+
const ENDPOINT_PATTERN = "/\/(v\d+)\/\w+\/([a-z]+)$/i";
14+
15+
class Beacon {
16+
private string $endpoint;
17+
private EvolvContext $context;
18+
private array $messages = [];
19+
private bool $v1Events;
20+
21+
public function __construct(string $endpoint, EvolvContext $context)
22+
{
23+
$this->endpoint = $endpoint;
24+
$this->context = $context;
25+
26+
preg_match(ENDPOINT_PATTERN, $endpoint, $matches);
27+
$this->v1Events = $matches && $matches[1] === 'v1' && $matches[2] === 'events';
28+
}
29+
30+
private function send($payload) {
31+
32+
$data = json_encode($payload);
33+
34+
echo $this->endpoint;
35+
36+
$curl = curl_init();
37+
38+
curl_setopt($curl, CURLOPT_URL, $this->endpoint);
39+
curl_setopt($curl, CURLOPT_POST, true);
40+
curl_setopt($curl, CURLOPT_HEADER, true);
41+
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
42+
43+
$headers = array(
44+
"Accept: application/json",
45+
"Content-Type: application/json",
46+
);
47+
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
48+
49+
$data = <<<DATA
50+
$data
51+
DATA;
52+
53+
echo '<pre>';
54+
print_r($data);
55+
echo '</pre>';
56+
57+
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
58+
59+
$res = curl_exec($curl);
60+
61+
echo "<pre>";
62+
print_r($res);
63+
echo "</pre>";
64+
65+
curl_close($curl);
66+
67+
$this->messages = [];
68+
}
69+
70+
private function wrapMessages()
71+
{
72+
return [
73+
'uid' => $this->context->uid,
74+
'client' => 'php-sdk',
75+
'messages' => $this->messages
76+
];
77+
}
78+
79+
private function transmit()
80+
{
81+
if (!count($this->messages)) {
82+
return;
83+
}
84+
85+
if ($this->v1Events) {
86+
foreach($this->messages as $message) {
87+
$editedMessage = $message;
88+
$editedMessage = $message['payload'] ?? [];
89+
$editedMessage['type'] = $message['type'];
90+
91+
$this->send($editedMessage);
92+
}
93+
} else {
94+
$this->send($this->wrapMessages());
95+
}
96+
}
97+
98+
public function emit(string $type, $payload, bool $flush = false)
99+
{
100+
$this->messages[] = [
101+
'type' => $type,
102+
'payload' => $payload,
103+
'timestamp' => time()
104+
];
105+
106+
$this->transmit();
107+
}
108+
109+
public function flush() {
110+
$this->transmit();
111+
}
112+
}

0 commit comments

Comments
 (0)