-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathHttpClientRequestHandler.php
103 lines (93 loc) · 2.93 KB
/
HttpClientRequestHandler.php
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
102
103
<?php
declare(strict_types=1);
namespace unreal4u\TelegramAPI;
use Exception;
use Psr\Http\Message\ResponseInterface;
use React\EventLoop\LoopInterface;
use React\Http\Browser;
use React\Http\Message\ResponseException;
use React\Promise\PromiseInterface;
use React\Socket\Connector;
use unreal4u\TelegramAPI\Exceptions\ClientException;
use unreal4u\TelegramAPI\InternalFunctionality\TelegramResponse;
/**
* Class HttpClientRequestHandler
*
* This class implements a request handler based on the react/http package.
*
* @package unreal4u\TelegramAPI
*/
class HttpClientRequestHandler implements RequestHandlerInterface
{
/**
* @var Browser
*/
protected $client;
/**
* HttpClientRequestHandler constructor.
*
* @param LoopInterface $loop
* @param array $options the options to pass to the socket connector
*
* @see https://github.com/reactphp/socket#connector
*/
public function __construct(LoopInterface $loop, array $options = [])
{
$this->client = new Browser($loop, new Connector($loop, $options));
}
/**
* Performs a GET request against the given URI
*
* @param string $uri
*
* @return PromiseInterface with a TelegramResponse on fulfill or exception on reject
*/
public function get(string $uri): PromiseInterface
{
return $this->processRequest($this->client->get($uri));
}
/**
* Performs a POST request against the given uri, with the given options
*
* @param string $uri
* @param array $options an array consisting of request options; known keys include 'headers' and 'body'.
*
* @return PromiseInterface with a TelegramResponse on fulfill or exception on reject
*/
public function post(string $uri, array $options): PromiseInterface
{
return $this->processRequest(
$this->client->post(
$uri,
$options['headers'] ?? [],
$options['body'] ?? null
)
);
}
/**
* Processes and unwraps an incoming request.
*
* @param \React\Promise\PromiseInterface $request
*
* @return PromiseInterface with a TelegramResponse on fulfill or exception on reject
*/
public function processRequest(PromiseInterface $request): PromiseInterface
{
return $request->then(
// Promise fulfilled
static function (ResponseInterface $response) {
return new TelegramResponse(
$response->getBody()->getContents(),
$response->getHeaders()
);
},
// Promise rejected
static function (Exception $e) {
if ($e instanceof ResponseException) {
throw ClientException::fromResponseException($e);
}
throw new ClientException($e->getMessage(), $e->getCode(), $e);
}
);
}
}