diff --git a/src/Client.php b/src/Client.php index 163f2ec..1c751c7 100644 --- a/src/Client.php +++ b/src/Client.php @@ -54,6 +54,12 @@ class Client */ protected $namespace = ''; + /** + * Timeout for creating the socket connection + * @var null|float + */ + protected $timeout; + /** * Singleton Reference @@ -77,6 +83,10 @@ public static function instance($name = 'default') public function __construct($instance_id = null) { $this->instance_id = $instance_id ?: uniqid(); + + if (empty($this->timeout)) { + $this->timeout = ini_get('default_socket_timeout'); + } } @@ -111,6 +121,9 @@ public function configure(array $options = array()) if (isset($options['namespace'])) { $this->namespace = $options['namespace']; } + if (isset($options['timeout'])) { + $this->timeout = $options['timeout']; + } return $this; } @@ -266,7 +279,7 @@ public function set($metric, $value) protected function send(array $data) { - $socket = @fsockopen('udp://' . $this->host, $this->port, $errno, $errstr); + $socket = @fsockopen('udp://' . $this->host, $this->port, $errno, $errstr, $this->timeout); if (! $socket) { throw new ConnectionException($this, '(' . $errno . ') ' . $errstr); } diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index f55a074..adf9c74 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -17,5 +17,18 @@ public function testInvalidHost() $this->client->increment('test'); } + public function testTimeoutSettingIsUsedWhenCreatingSocketIfProvided() + { + $this->client->configure(array( + 'host' => 'localhost', + 'timeout' => 123 + )); + $this->assertAttributeSame(123, 'timeout', $this->client); + } + + public function testTimeoutDefaultsToPhpIniDefaultSocketTimeout() + { + $this->assertAttributeSame(ini_get('default_socket_timeout'), 'timeout', $this->client); + } }