summaryrefslogtreecommitdiffstats
path: root/vendor/clue/connection-manager-extra/src/Multiple/ConnectionManagerConcurrent.php
blob: c1eb9cf1a46a579c7fcbf661b9269d624bcf803a (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
36
<?php

namespace ConnectionManager\Extra\Multiple;

use ConnectionManager\Extra\Multiple\ConnectionManagerConsecutive;
use React\Promise;
use React\Promise\CancellablePromiseInterface;

class ConnectionManagerConcurrent extends ConnectionManagerConsecutive
{
    public function connect($uri)
    {
        $all = array();
        foreach ($this->managers as $connector) {
            /* @var $connection Connector */
            $all []= $connector->connect($uri);
        }
        return Promise\any($all)->then(function ($conn) use ($all) {
            // a connection attempt succeeded
            // => cancel all pending connection attempts
            foreach ($all as $promise) {
                if ($promise instanceof CancellablePromiseInterface) {
                    $promise->cancel();
                }

                // if promise resolves despite cancellation, immediately close stream
                $promise->then(function ($stream) use ($conn) {
                    if ($stream !== $conn) {
                        $stream->close();
                    }
                });
            }
            return $conn;
        });
    }
}