Debian Codegraph @

vendor/clue/connection-manager-extra/src/Multiple/ConnectionManagerConsecutive.php

raw
1 <?php
2
3 namespace ConnectionManager\Extra\Multiple;
4
5 use React\Promise;
6 use React\Promise\PromiseInterface;
7 use React\Socket\ConnectorInterface;
8 use UnderflowException;
9
10 class ConnectionManagerConsecutive implements ConnectorInterface
11 {
12 protected $managers;
13
14 /**
15 *
16 * @param ConnectorInterface[] $managers
17 */
18 public function __construct(array $managers)
19 {
20 if (!$managers) {
21 throw new \InvalidArgumentException('List of connectors must not be empty');
22 }
23 $this->managers = $managers;
24 }
25
26 public function connect($uri)
27 {
28 return $this->tryConnection($this->managers, $uri);
29 }
30
31 /**
32 *
33 * @param ConnectorInterface[] $managers
34 * @param string $uri
35 * @return Promise
36 * @internal
37 */
38 public function tryConnection(array $managers, $uri)
39 {
40 return new Promise\Promise(function ($resolve, $reject) use (&$managers, &$pending, $uri) {
41 $try = function () use (&$try, &$managers, $uri, $resolve, $reject, &$pending) {
42 if (!$managers) {
43 return $reject(new UnderflowException('No more managers to try to connect through'));
44 }
45
46 $manager = array_shift($managers);
47 $pending = $manager->connect($uri);
48 $pending->then($resolve, $try);
49 };
50
51 $try();
52 }, function ($_, $reject) use (&$managers, &$pending) {
53 // stop retrying, reject results and cancel pending attempt
54 $managers = array();
55 $reject(new \RuntimeException('Cancelled'));
56
57 if ($pending instanceof PromiseInterface && \method_exists($pending, 'cancel')) {
58 $pending->cancel();
59 }
60 });
61 }
62 }