Skip to content

Commit

Permalink
Merge pull request #28 from graze/add-read-timeout
Browse files Browse the repository at this point in the history
Add read timeout
  • Loading branch information
brendankay committed Jun 30, 2020
2 parents bf0b226 + 7d93cb4 commit b8091d6
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/TelnetClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,21 @@ public function getSocket()
return $this->socket;
}

/**
* @param float $timeout
*/
public function setReadTimeout($timeout)
{
if (!$this->socket) {
throw new TelnetException('cannot set read timeout, socket does not exist (call connect() first)');
}

$sec = floor($timeout);
$usec = round(fmod($timeout, 1) * 1000000);

$this->socket->setOption(SOL_SOCKET, SO_RCVTIMEO, ['sec' => $sec, 'usec' => $usec]);
}

/**
* @param string $command
* @param string $prompt
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/TelnetClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,4 +291,46 @@ public function testFactory()
$client = TelnetClient::factory();
$this->assertInstanceOf(TelnetClient::class, $client);
}

/**
* @dataProvider setReadTimeoutDataProvider
* @param float $timeout
* @param int $expectedSec
* @param int $expectedUsec
*/
public function testSetReadTimeout($timeout, $expectedSec, $expectedUsec)
{
$client = m::mock(TelnetClient::class)->makePartial();

$socket = m::mock(Socket::class)
->shouldReceive('setOption')
->with(SOL_SOCKET, SO_RCVTIMEO, ['sec' => $expectedSec, 'usec' => $expectedUsec])
->shouldReceive('close')
->getMock();

$client->setSocket($socket);

$client->setReadTimeout($timeout);
}

/**
* @return mixed[]
*/
public function setReadTimeoutDataProvider()
{
return [
[1, 1, 0],
[0.5, 0, 500000],
[2.345, 2, 345000],
];
}

public function testSetReadTimeoutException()
{
$this->setExpectedException(TelnetExceptionInterface::class);

$client = m::mock(TelnetClient::class)->makePartial();

$client->setReadTimeout(1);
}
}

0 comments on commit b8091d6

Please sign in to comment.