Debian Codegraph @

vendor/react/dns/src/Query/TimeoutExecutor.php

raw
1 <?php
2
3 namespace React\Dns\Query;
4
5 use React\EventLoop\Loop;
6 use React\EventLoop\LoopInterface;
7 use React\Promise\Promise;
8
9 final class TimeoutExecutor implements ExecutorInterface
10 {
11 private $executor;
12 private $loop;
13 private $timeout;
14
15 /**
16 * @param ExecutorInterface $executor
17 * @param float $timeout
18 * @param ?LoopInterface $loop
19 */
20 public function __construct(ExecutorInterface $executor, $timeout, $loop = null)
21 {
22 if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
23 throw new \InvalidArgumentException('Argument #3 ($loop) expected null|React\EventLoop\LoopInterface');
24 }
25
26 $this->executor = $executor;
27 $this->loop = $loop ?: Loop::get();
28 $this->timeout = $timeout;
29 }
30
31 public function query(Query $query)
32 {
33 $promise = $this->executor->query($query);
34
35 $loop = $this->loop;
36 $time = $this->timeout;
37 return new Promise(function ($resolve, $reject) use ($loop, $time, $promise, $query) {
38 $timer = null;
39 $promise = $promise->then(function ($v) use (&$timer, $loop, $resolve) {
40 if ($timer) {
41 $loop->cancelTimer($timer);
42 }
43 $timer = false;
44 $resolve($v);
45 }, function ($v) use (&$timer, $loop, $reject) {
46 if ($timer) {
47 $loop->cancelTimer($timer);
48 }
49 $timer = false;
50 $reject($v);
51 });
52
53 // promise already resolved => no need to start timer
54 if ($timer === false) {
55 return;
56 }
57
58 // start timeout timer which will cancel the pending promise
59 $timer = $loop->addTimer($time, function () use ($time, &$promise, $reject, $query) {
60 $reject(new TimeoutException(
61 'DNS query for ' . $query->describe() . ' timed out'
62 ));
63
64 // Cancel pending query to clean up any underlying resources and references.
65 // Avoid garbage references in call stack by passing pending promise by reference.
66 assert(\method_exists($promise, 'cancel'));
67 $promise->cancel();
68 $promise = null;
69 });
70 }, function () use (&$promise) {
71 // Cancelling this promise will cancel the pending query, thus triggering the rejection logic above.
72 // Avoid garbage references in call stack by passing pending promise by reference.
73 assert(\method_exists($promise, 'cancel'));
74 $promise->cancel();
75 $promise = null;
76 });
77 }
78 }