| 1 |
<?php |
| 2 |
|
| 3 |
namespace ConnectionManager\Extra; |
| 4 |
|
| 5 |
use React\EventLoop\Loop; |
| 6 |
use React\EventLoop\LoopInterface; |
| 7 |
use React\Promise\Timer; |
| 8 |
use React\Socket\ConnectorInterface; |
| 9 |
|
| 10 |
class ConnectionManagerTimeout implements ConnectorInterface |
| 11 |
{ |
| 12 |
/** @var ConnectorInterface */ |
| 13 |
private $connectionManager; |
| 14 |
|
| 15 |
/** @var float */ |
| 16 |
private $timeout; |
| 17 |
|
| 18 |
/** @var LoopInterface */ |
| 19 |
private $loop; |
| 20 |
|
| 21 |
/** |
| 22 |
* @param ConnectorInterface $connectionManager |
| 23 |
* @param float $timeout |
| 24 |
* @param ?LoopInterface $loop |
| 25 |
*/ |
| 26 |
public function __construct(ConnectorInterface $connectionManager, $timeout, $loop = null) |
| 27 |
{ |
| 28 |
if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 |
| 29 |
throw new \InvalidArgumentException('Argument #3 ($loop) expected null|React\EventLoop\LoopInterface'); |
| 30 |
} |
| 31 |
|
| 32 |
$this->connectionManager = $connectionManager; |
| 33 |
$this->timeout = $timeout; |
| 34 |
$this->loop = $loop ?: Loop::get(); |
| 35 |
} |
| 36 |
|
| 37 |
public function connect($uri) |
| 38 |
{ |
| 39 |
$promise = $this->connectionManager->connect($uri); |
| 40 |
|
| 41 |
return Timer\timeout($promise, $this->timeout, $this->loop)->then(null, function ($e) use ($promise) { |
| 42 |
// connection successfully established but timeout already expired => close successful connection |
| 43 |
$promise->then(function ($connection) { |
| 44 |
$connection->end(); |
| 45 |
}); |
| 46 |
|
| 47 |
throw $e; |
| 48 |
}); |
| 49 |
} |
| 50 |
} |