Completed
Push — master ( 7dbde1...631665 )
by Camilo
11s
created

HttpClientRequestHandlerAmp::processRequest()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 1
nop 1
dl 0
loc 11
ccs 0
cts 2
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace unreal4u\TelegramAPI;
6
7
use Amp\Artax\DefaultClient;
8
use Amp\Artax\Request;
9
use Amp\Artax\Response;
10
use Amp\Promise;
11
use React\Promise\PromiseInterface;
12
use unreal4u\TelegramAPI\Exceptions\ClientException;
13
use unreal4u\TelegramAPI\InternalFunctionality\TelegramResponse;
14
15
/**
16
 * @param Promise $promise
17
 * @return \React\Promise\PromiseInterface
18
 */
19
function reactAdapt(Promise $promise) {
20
    $deferred = new \React\Promise\Deferred();
21
22
    $promise->onResolve(function ($error = null, $result = null) use ($deferred) {
23
        if ($error) {
24
            $deferred->reject($error);
25
        } else {
26
            $deferred->resolve($result);
27
        }
28
    });
29
30
    return $deferred->promise();
31
}
32
33
class HttpClientRequestHandlerAmp implements RequestHandlerInterface {
34
35
    /**
36
     * @var DefaultClient
37
     */
38
    private $client;
39
40
    public function __construct() {
41
        $this->client = new DefaultClient;
42
    }
43
44
    /**
45
     * @param string $uri
46
     *
47
     * @return PromiseInterface
48
     */
49
    public function get(string $uri): PromiseInterface {
50
         $request = (new Request($uri))->withMethod('GET');
51
52
         return $this->processRequest($request);
53
    }
54
55
    /**
56
     * @param string $uri
57
     * @param array $formFields
58
     *
59
     * @return PromiseInterface
60
     */
61
    public function post(string $uri, array $formFields): PromiseInterface {
62
        $request = (new Request($uri))->withMethod('POST');
63
64
        if (!empty($formFields['headers']))
65
            $request = $request->withHeaders($formFields['headers']);
66
67
        if (!empty($formFields['body']))
68
            $request = $request->withBody($formFields['body']);
69
70
        return $this->processRequest($request);
71
    }
72
73
    /**
74
     * @param Request $request
75
     *
76
     * @return PromiseInterface
77
     */
78
    private function processRequest(Request $request) {
79
        return reactAdapt(\Amp\call(function () use ($request) {
80
            /** @var Response $response */
81
            $response = yield $this->client->request($request);
82
83
            if ($response->getStatus() >= 400)
84
                throw new ClientException($response->getReason(), $response->getStatus());
85
86
            return new TelegramResponse(yield $response->getBody(), $response->getHeaders());
87
        }));
88
    }
89
}
90