|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Programic\Tools\Services\Analytics; |
| 4 | + |
| 5 | +use Illuminate\Support\Collection; |
| 6 | +use Programic\Tools\Contracts\AnalyticsClient; |
| 7 | + |
| 8 | +class Databox implements AnalyticsClient |
| 9 | +{ |
| 10 | + private $token; |
| 11 | + |
| 12 | + public function __construct($token) |
| 13 | + { |
| 14 | + $this->token = $token; |
| 15 | + |
| 16 | + if (!$token) { |
| 17 | + throw new \Exception('Databox token must be set'); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public function send(Collection $data): array |
| 22 | + { |
| 23 | + $postData = []; |
| 24 | + |
| 25 | + $data->each(function ($queue) use (&$postData) { |
| 26 | + $name = $queue[0]->queue; |
| 27 | + $count = $queue->sum('count'); |
| 28 | + |
| 29 | + foreach ($queue as $item) { |
| 30 | + $postData[] = [ |
| 31 | + "\$queue_{$item->queue}" => $item->count, |
| 32 | + 'event' => str_replace('\\\\', '\\', (trim($item->event, '"'))), |
| 33 | + 'date' => now()->format('c'), |
| 34 | + ]; |
| 35 | + } |
| 36 | + }); |
| 37 | + |
| 38 | + $ch = curl_init(); |
| 39 | + curl_setopt($ch, CURLOPT_URL,'https://push.databox.com'); |
| 40 | + curl_setopt($ch, CURLOPT_POST, 1); |
| 41 | + curl_setopt($ch, CURLOPT_USERPWD, "$this->token:"); |
| 42 | + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['data' => $postData])); |
| 43 | + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
| 44 | + |
| 45 | + $headers = [ |
| 46 | + 'Accept: application/vnd.databox.v2+json', |
| 47 | + 'Content-Type: application/json', |
| 48 | + ]; |
| 49 | + |
| 50 | + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); |
| 51 | + |
| 52 | + $server_output = curl_exec($ch); |
| 53 | + |
| 54 | + curl_close($ch); |
| 55 | + |
| 56 | + return json_decode($server_output, true); |
| 57 | + } |
| 58 | +} |
0 commit comments