-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAmpHttpRequestsClass.php
More file actions
101 lines (90 loc) · 2.58 KB
/
AmpHttpRequestsClass.php
File metadata and controls
101 lines (90 loc) · 2.58 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
use Amp\Artax\DefaultClient;
use Amp\Artax\Request;
use Amp\Artax\Response;
use Amp\Coroutine;
use Amp\Promise;
use Amp\Loop;
use function Amp\call;
/**
* Class AmpClass
*/
class AmpHttpRequestsClass
{
/** @var array */
protected $urls = [];
/** @var DefaultClient */
protected $client;
public function __construct()
{
$this->client = new DefaultClient;
$this->client->setOption(DefaultClient::OP_TRANSFER_TIMEOUT, 15000);
}
/**
* @param string $url
* @param array|null $postBody
*/
public function addUrl(string $url, ?array $postBody = null): void
{
array_push($this->urls, [
'url' => $url,
'body' => $postBody,
]);
}
public function run()
{
$result = [];
Loop::run(function () use (&$result) {
try {
/** @var Coroutine[] $promises */
$promises = [];
foreach ($this->urls as $urlInfo) {
$promises[$urlInfo['url']] = call($this->getRequestHandler(), $urlInfo['url'],
$urlInfo['body']);
}
$result = yield Promise\any($promises);
$result = $this->prepareResult($result);
} catch (Amp\Artax\HttpException $error) {
//echo $error;
}
});
return $result;
}
protected function prepareResult(array $result)
{
$data = [];
/** @var Exception[] $exceptions */
$exceptions = array_shift($result);
$responses = array_shift($result);
foreach ($responses as $url => $response) {
$data[$url] = [
'status' => true,
'data' => $response,
];
}
foreach ($exceptions as $url => $error) {
$data[$url] = [
'status' => false,
'data' => $error->getMessage(),
];
}
return $data;
}
/**
* @return Closure
*/
protected function getRequestHandler(): Closure
{
return function (string $url, ?array $body) {
$time = time();
$request = new Request($url, $body ? 'POST' : 'GET');
if (!empty($body)) {
$request = $request->withBody(json_encode($body));
}
/** @var Response $response */
$response = yield $this->client->request($request);
print 'Finished url: ' . $url . ' with time ' . (time() - $time) . ' s' . PHP_EOL;
return $response->getBody();
};
}
}