diff --git a/src/Telemetry/Collector.php b/src/Telemetry/Collector.php index c01e974..521d8ec 100644 --- a/src/Telemetry/Collector.php +++ b/src/Telemetry/Collector.php @@ -11,9 +11,9 @@ class Collector private $config; private $client; - public function __construct(string $id, string $apiKey) + public function __construct(string $id, string $apiKey, Client $http) { - $this->client = new Client(); + $this->client = $http; $this->data = []; $this->config = [ 'id' => $id, @@ -26,9 +26,13 @@ public function setParams($params) $this->params = $params; } - public static function create($config) + public static function create($config, Client $http) { - $collector = new Collector($config['id'], $config['api_key']); + if (!isset($config['id']) || !isset($config['api_key'])) { + throw new \InvalidArgumentException('The id and api_key parameters are required.'); + } + + $collector = new Collector($config['id'], $config['api_key'], $http); $collector->start(); @@ -71,6 +75,10 @@ private function start() private function sendBeacon($body) { + if ($this->params == null || !isset($this->params['endpoint'])) { + return; + } + $url = $this->params['endpoint'] . '?api-key=' . $this->config['api_key']; $this->client->requestAsync('POST', $url, [ diff --git a/tests/Feature/ClientTest.php b/tests/Feature/ClientTest.php index 64a9af0..283d4b8 100644 --- a/tests/Feature/ClientTest.php +++ b/tests/Feature/ClientTest.php @@ -13,16 +13,22 @@ test('basic fulltext search', function () { // Create a mock handler and queue a response. $mock = new MockHandler([ + // initial request to get the collect URL new Response(200, [], json_encode([ 'collectUrl' => 'mock-url', 'deploymentID' => 'mock-deployment-id', 'index' => 'mock-index', ])), + // search request new Response(200, [], json_encode([ 'hits' => [['id' => 2]], 'elapsed' => 0.2, 'count' => 1, ])), + // telemetry data collection + new Response(200, [], json_encode([ + 'message' => 'Telemetry data collected successfully', + ])), ]); $handlerStack = HandlerStack::create($mock);