public function write($buf)
{
$null = null;
$write = array($this->stream);
// fwrite to a socket may be partial, so loop until we
// are done with the entire buffer
$failedWriteAttempts = 0;
$written = 0;
$buflen = strlen($buf);
while ($written < $buflen) {
// wait for stream to become available for writing
$writable = stream_select($null, $write, $null, $this->sendTimeoutSec, $this->sendTimeoutUsec);
if ($writable > 0) {
if ($buflen - $written > self::MAX_WRITE_BUFFER) {
// write max buffer size
$wrote = fwrite($this->stream, substr($buf, $written, self::MAX_WRITE_BUFFER));
} else {
// write remaining buffer bytes to stream
$wrote = fwrite($this->stream, substr($buf, $written));
}
if ($wrote === -1 || $wrote === false) {
throw new \Kafka\Exception\Socket('Could not write ' . strlen($buf) . ' bytes to stream, completed writing only ' . $written . ' bytes');
} elseif ($wrote === 0) {
// Increment the number of times we have failed
$failedWriteAttempts++;
if ($failedWriteAttempts > $this->maxWriteAttempts) {
throw new \Kafka\Exception\Socket('After ' . $failedWriteAttempts . ' attempts could not write ' . strlen($buf) . ' bytes to stream, completed writing only ' . $written . ' bytes');
}
} else {
// If we wrote something, reset our failed attempt counter
$failedWriteAttempts = 0;
}
$written += $wrote;
continue;
}
if (false !== $writable) {
$res = stream_get_meta_data($this->stream);
if (!empty($res['timed_out'])) {
throw new \Kafka\Exception\SocketTimeout('Timed out writing ' . strlen($buf) . ' bytes to stream after writing ' . $written . ' bytes');
}
}
throw new \Kafka\Exception\Socket('Could not write ' . strlen($buf) . ' bytes to stream');
}
return $written;
}