summaryrefslogtreecommitdiffstats
path: root/vendor/clue/connection-manager-extra/src/ConnectionManagerTimeout.php
blob: 5ec0872b4e214ca229f0364bbb25eab5962c182a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php

namespace ConnectionManager\Extra;

use React\Socket\ConnectorInterface;
use React\EventLoop\LoopInterface;
use React\Promise\Timer;

class ConnectionManagerTimeout implements ConnectorInterface
{
    private $connectionManager;
    private $timeout;
    private $loop;

    public function __construct(ConnectorInterface $connectionManager, $timeout, LoopInterface $loop)
    {
        $this->connectionManager = $connectionManager;
        $this->timeout = $timeout;
        $this->loop = $loop;
    }

    public function connect($uri)
    {
        $promise = $this->connectionManager->connect($uri);

        return Timer\timeout($promise, $this->timeout, $this->loop)->then(null, function ($e) use ($promise) {
            // connection successfully established but timeout already expired => close successful connection
            $promise->then(function ($connection) {
                $connection->end();
            });

            throw $e;
        });
    }
}