Debian Codegraph @

vendor/clue/connection-manager-extra/src/ConnectionManagerRepeat.php

raw
1 <?php
2
3 namespace ConnectionManager\Extra;
4
5 use React\Socket\ConnectorInterface;
6 use InvalidArgumentException;
7 use Exception;
8 use React\Promise\Promise;
9 use React\Promise\PromiseInterface;
10
11 class ConnectionManagerRepeat implements ConnectorInterface
12 {
13 protected $connectionManager;
14 protected $maximumTries;
15
16 public function __construct(ConnectorInterface $connectionManager, $maximumTries)
17 {
18 if ($maximumTries < 1) {
19 throw new InvalidArgumentException('Maximum number of tries must be >= 1');
20 }
21 $this->connectionManager = $connectionManager;
22 $this->maximumTries = $maximumTries;
23 }
24
25 public function connect($uri)
26 {
27 $tries = $this->maximumTries;
28 $connector = $this->connectionManager;
29
30 return new Promise(function ($resolve, $reject) use ($uri, &$pending, &$tries, $connector) {
31 $try = function ($error = null) use (&$try, &$pending, &$tries, $uri, $connector, $resolve, $reject) {
32 if ($tries > 0) {
33 --$tries;
34 $pending = $connector->connect($uri);
35 $pending->then($resolve, $try);
36 } else {
37 $reject(new Exception('Connection still fails even after retrying', 0, $error));
38 }
39 };
40
41 $try();
42 }, function ($_, $reject) use (&$pending, &$tries) {
43 // stop retrying, reject results and cancel pending attempt
44 $tries = 0;
45 $reject(new \RuntimeException('Cancelled'));
46
47 if ($pending instanceof PromiseInterface && \method_exists($pending, 'cancel')) {
48 $pending->cancel();
49 }
50 });
51 }
52 }