| 1 |
<?php |
| 2 |
|
| 3 |
namespace PostHog\Consumer; |
| 4 |
|
| 5 |
use PostHog\HttpClient; |
| 6 |
use PostHog\QueueConsumer; |
| 7 |
|
| 8 |
class LibCurl extends QueueConsumer |
| 9 |
{ |
| 10 |
protected $type = "LibCurl"; |
| 11 |
/** |
| 12 |
* @var HttpClient |
| 13 |
*/ |
| 14 |
private $httpClient; |
| 15 |
|
| 16 |
/** |
| 17 |
* Creates a new queued libcurl consumer |
| 18 |
* @param string $apiKey |
| 19 |
* @param array $options |
| 20 |
* boolean "debug" - whether to use debug output, wait for response. |
| 21 |
* number "max_queue_size" - the max size of messages to enqueue |
| 22 |
* number "batch_size" - how many messages to send in a single request |
| 23 |
*/ |
| 24 |
public function __construct($apiKey, $options = []) |
| 25 |
{ |
| 26 |
parent::__construct($apiKey, $options); |
| 27 |
$this->httpClient = new HttpClient( |
| 28 |
$this->host, |
| 29 |
$this->ssl(), |
| 30 |
$this->maximum_backoff_duration, |
| 31 |
$this->compress_request, |
| 32 |
$this->debug(), |
| 33 |
$this->options['error_handler'] ?? null |
| 34 |
); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Define getter method for consumer type |
| 39 |
* |
| 40 |
* @return string |
| 41 |
*/ |
| 42 |
public function getConsumer() |
| 43 |
{ |
| 44 |
return $this->type; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Make a sync request to our API. If debug is |
| 49 |
* enabled, we wait for the response |
| 50 |
* and retry once to diminish impact on performance. |
| 51 |
* @param array $messages array of all the messages to send |
| 52 |
* @return boolean whether the request succeeded |
| 53 |
*/ |
| 54 |
public function flushBatch($messages) |
| 55 |
{ |
| 56 |
$body = $this->payload($messages); |
| 57 |
$payload = json_encode($body); |
| 58 |
|
| 59 |
// Verify message size is below than 32KB |
| 60 |
if (strlen($payload) >= 32 * 1024) { |
| 61 |
if ($this->debug()) { |
| 62 |
$msg = "Message size is larger than 32KB"; |
| 63 |
error_log("[PostHog][" . $this->type . "] " . $msg); |
| 64 |
} |
| 65 |
|
| 66 |
return false; |
| 67 |
} |
| 68 |
|
| 69 |
if ($this->compress_request) { |
| 70 |
$payload = gzencode($payload); |
| 71 |
} |
| 72 |
|
| 73 |
return $this->httpClient->sendRequest( |
| 74 |
'/batch/', |
| 75 |
$payload, |
| 76 |
[ |
| 77 |
// Send user agent in the form of {library_name}/{library_version} as per RFC 7231. |
| 78 |
"User-Agent: {$messages[0]['library']}/{$messages[0]['library_version']}", |
| 79 |
] |
| 80 |
)->getResponse(); |
| 81 |
} |
| 82 |
} |
| 83 |
|