Skip to content

Commit

Permalink
Merge pull request #47 from sixlive/add-timeout
Browse files Browse the repository at this point in the history
Add timeout
  • Loading branch information
adamwathan authored Sep 18, 2017
2 parents 390efa5 + cae19d9 commit 018bac4
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/Zttp.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,13 @@ function withDigestAuth($username, $password)
});
}

function timeout($seconds)
{
$this->options['timeout'] = $seconds;

return $this;
}

function beforeSending($callback)
{
return tap($this, function () use ($callback) {
Expand Down Expand Up @@ -147,9 +154,13 @@ function delete($url, $params = [])

function send($method, $url, $options)
{
return new ZttpResponse($this->buildClient()->request($method, $url, $this->mergeOptions([
'query' => $this->parseQueryParams($url),
], $options)));
try {
return new ZttpResponse($this->buildClient()->request($method, $url, $this->mergeOptions([
'query' => $this->parseQueryParams($url),
], $options)));
} catch (\GuzzleHttp\Exception\ConnectException $e) {
throw new ConnectionException($e->getMessage(), 0, $e);
}
}

function buildClient()
Expand Down Expand Up @@ -300,6 +311,8 @@ function __call($method, $args)
}
}

class ConnectionException extends \Exception {}

function tap($value, $callback) {
$callback($value);
return $value;
Expand Down
9 changes: 9 additions & 0 deletions tests/ZttpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,15 @@ function can_use_basic_auth()

$this->assertTrue($response->isOk());
}

/**
* @test
* @expectedException \Zttp\ZttpConnectException
*/
function client_will_force_timeout()
{
Zttp::timeout(1)->get($this->url('/timeout'));
}
}

class ZttpServer
Expand Down
4 changes: 4 additions & 0 deletions tests/server/public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ function build_response($request)
return "A simple string response";
});

$app->get('/timeout', function () {
sleep(2);
});

$app->get('/basic-auth', function () {
$headers = [
(bool) preg_match('/Basic\s[a-zA-Z0-9]+/', app('request')->header('Authorization')),
Expand Down

0 comments on commit 018bac4

Please sign in to comment.