diff --git a/.gitignore b/.gitignore index de6e5ad..373b920 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ composer.phar test/analytics.log /.vscode .phplint-cache +/.idea diff --git a/lib/Segment/Client.php b/lib/Segment/Client.php index 9ac6be5..6b3e931 100644 --- a/lib/Segment/Client.php +++ b/lib/Segment/Client.php @@ -21,17 +21,26 @@ class Segment_Client { * */ public function __construct($secret, $options = array()) { + $consumers = array( - "socket" => "Segment_Consumer_Socket", - "file" => "Segment_Consumer_File", - "fork_curl" => "Segment_Consumer_ForkCurl", - "lib_curl" => "Segment_Consumer_LibCurl" + "socket" => "Segment_Consumer_Socket", + "file" => "Segment_Consumer_File", + "fork_curl" => "Segment_Consumer_ForkCurl", + "lib_curl" => "Segment_Consumer_LibCurl" ); - // Use our socket libcurl by default $consumer_type = isset($options["consumer"]) ? $options["consumer"] : "lib_curl"; + if (!array_key_exists($consumer_type, $consumers) && class_exists($consumer_type)) { + if (!is_subclass_of($consumer_type, Segment_Consumer::class)) { + throw new Exception('Consumers must extend the Segment_Consumer abstract class'); + } + // Try to resolve it by class name + $this->consumer = new $consumer_type($secret, $options); + return; + } + $Consumer = $consumers[$consumer_type]; $this->consumer = new $Consumer($secret, $options); @@ -131,6 +140,14 @@ public function flush() { return true; } + /** + * @return Segment_Consumer + */ + public function getConsumer() { + return $this->consumer; + } + + /** * Formats a timestamp by making sure it is set * and converting it to iso8601. diff --git a/test/ClientTest.php b/test/ClientTest.php new file mode 100644 index 0000000..754f4c5 --- /dev/null +++ b/test/ClientTest.php @@ -0,0 +1,31 @@ +assertInstanceOf(Segment_Consumer_LibCurl::class, $client->getConsumer()); + } + + /** @test */ + public function can_provide_the_consumer_configuration_as_string() + { + $client = new Segment_Client('foobar', [ + 'consumer' => 'fork_curl', + ]); + $this->assertInstanceOf(Segment_Consumer_ForkCurl::class, $client->getConsumer()); + } + + /** @test */ + public function can_provide_a_class_namespace_as_consumer_configuration() + { + $client = new Segment_Client('foobar', [ + 'consumer' => Segment_Consumer_ForkCurl::class, + ]); + $this->assertInstanceOf(Segment_Consumer_ForkCurl::class, $client->getConsumer()); + } +}