-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCrm.php
92 lines (74 loc) · 2.4 KB
/
Crm.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
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
namespace Remp\MailerModule\Models\Segment;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use JsonMachine\Items;
use Psr\Http\Message\StreamInterface;
class Crm implements ISegment
{
const PROVIDER_ALIAS = 'crm-segment';
const ENDPOINT_LIST = 'api/v1/user-segments/list';
const ENDPOINT_USERS = 'api/v1/user-segments/users';
private $baseUrl;
private $token;
public function __construct(string $baseUrl, string $token)
{
$this->baseUrl = $baseUrl;
$this->token = $token;
}
public function provider(): string
{
return static::PROVIDER_ALIAS;
}
public function list(): array
{
$response = $this->request(static::ENDPOINT_LIST);
$stream = \GuzzleHttp\Psr7\StreamWrapper::getResource($response);
try {
$segments = [];
foreach (Items::fromStream($stream, ['pointer' => '/segments']) as $segment) {
$segments[] = [
'name' => $segment->name,
'provider' => static::PROVIDER_ALIAS,
'code' => $segment->code,
'group' => $segment->group->name,
];
}
} finally {
fclose($stream);
}
return $segments;
}
public function users(array $segment): array
{
$response = $this->request(static::ENDPOINT_USERS, ['code' => $segment['code']]);
$stream = \GuzzleHttp\Psr7\StreamWrapper::getResource($response);
try {
$userIds = [];
foreach (Items::fromStream($stream, ['pointer' => '/users']) as $user) {
$userIds[] = $user->id;
}
} finally {
fclose($stream);
}
return $userIds;
}
private function request(string $url, array $query = []): StreamInterface
{
$client = new Client([
'base_uri' => $this->baseUrl,
'headers' => [
'Authorization' => 'Bearer ' . $this->token,
]
]);
try {
$response = $client->get($url, [
'query' => $query,
]);
return $response->getBody();
} catch (ConnectException $connectException) {
throw new SegmentException("Could not connect to Segment:{$url} endpoint: {$connectException->getMessage()}");
}
}
}