Completed
Push — master ( 1298c9...8e45b5 )
by Camilo
03:58 queued 01:54
created

TgLog::performApiRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1.008

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 1
dl 0
loc 13
ccs 8
cts 10
cp 0.8
crap 1.008
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 Psr\Log\LoggerInterface;
8
use React\Promise\PromiseInterface;
9
use unreal4u\TelegramAPI\Abstracts\TelegramMethods;
10
use unreal4u\TelegramAPI\InternalFunctionality\DummyLogger;
11
use unreal4u\TelegramAPI\InternalFunctionality\PostOptionsConstructor;
12
use unreal4u\TelegramAPI\InternalFunctionality\TelegramDocument;
13
use unreal4u\TelegramAPI\InternalFunctionality\TelegramResponse;
14
use unreal4u\TelegramAPI\Telegram\Types\File;
15
16
/**
17
 * The main API which does it all
18
 */
19
class TgLog
20
{
21
    /**
22
     * @var RequestHandlerInterface
23
     */
24
    protected $requestHandler;
25
26
    /**
27
     * @var PostOptionsConstructor
28
     */
29
    protected $formConstructor;
30
31
    /**
32
     * Stores the token
33
     * @var string
34
     */
35
    private $botToken;
36
37
    /**
38
     * Contains an instance to a PSR-3 compatible logger
39
     * @var LoggerInterface
40
     */
41
    protected $logger;
42
43
    /**
44
     * Stores the API URL from Telegram
45
     * @var string
46
     */
47
    private $apiUrl;
48
49
    /**
50
     * @var string
51
     */
52
    protected $methodName = '';
53
54
    /**
55
     * TelegramLog constructor.
56
     *
57
     * @param string $botToken
58
     * @param RequestHandlerInterface $handler
59
     * @param LoggerInterface $logger
60
     */
61 40
    public function __construct(string $botToken, RequestHandlerInterface $handler, LoggerInterface $logger = null)
62
    {
63 40
        $this->botToken = $botToken;
64
65
        // Initialize new dummy logger (PSR-3 compatible) if not injected
66 40
        if ($logger === null) {
67 40
            $logger = new DummyLogger();
68
        }
69 40
        $this->logger = $logger;
70
71 40
        $this->requestHandler = $handler;
72 40
        $this->formConstructor = new PostOptionsConstructor();
73 40
        $this->apiUrl = 'https://api.telegram.org/bot' . $this->botToken . '/';
74 40
    }
75
76
    /**
77
     * Performs the request to the Telegram servers
78
     *
79
     * @param TelegramMethods $method
80
     *
81
     * @return PromiseInterface
82
     * @throws \unreal4u\TelegramAPI\Exceptions\MissingMandatoryField
83
     */
84 31
    public function performApiRequest(TelegramMethods $method): PromiseInterface
85
    {
86 31
        $this->logger->debug('Request for async API call, resetting internal values', [get_class($method)]);
87 31
        $this->resetObjectValues();
88 31
        $option = $this->formConstructor->constructOptions($method);
89 29
        return $this->sendRequestToTelegram($method, $option)
90 24
            ->then(function (TelegramResponse $response) use ($method) {
91 24
                return $method::bindToObject($response, $this->logger);
92
            }, function ($error) {
93
                $this->logger->error($error);
94
                throw $error;
95 24
            });
96
    }
97
98
    /**
99
     * @param File $file
100
     *
101
     * @return PromiseInterface
102
     */
103
    public function downloadFile(File $file): PromiseInterface
104
    {
105
        $url = 'https://api.telegram.org/file/bot' . $this->botToken . '/' . $file->file_path;
106
        $this->logger->debug('About to perform request to begin downloading file');
107
108
        return $this->requestHandler->get($url)->then(
109
            function (TelegramResponse $rawData) {
110
                return new TelegramDocument($rawData);
111
            }
112
        );
113
    }
114
115
    /**
116
     * @param TelegramMethods $method
117
     * @param array $formData
118
     *
119
     * @return PromiseInterface
120
     */
121
    protected function sendRequestToTelegram(TelegramMethods $method, array $formData): PromiseInterface
122
    {
123
        $this->logger->debug('About to perform async HTTP call to Telegram\'s API');
124
        return $this->requestHandler->post($this->composeApiMethodUrl($method), $formData);
125
    }
126
127
    /**
128
     * Resets everything to the default values
129
     *
130
     * @return TgLog
131
     */
132 31
    final protected function resetObjectValues(): TgLog
133
    {
134 31
        $this->formConstructor->formType = 'application/x-www-form-urlencoded';
135 31
        return $this;
136
    }
137
138
    /**
139
     * Builds up the URL with which we can work with
140
     *
141
     * All methods in the Bot API are case-insensitive.
142
     * All queries must be made using UTF-8.
143
     *
144
     * @see https://core.telegram.org/bots/api#making-requests
145
     *
146
     * @param TelegramMethods $call
147
     * @return string
148
     */
149 30
    protected function composeApiMethodUrl(TelegramMethods $call): string
150
    {
151 30
        $completeClassName = get_class($call);
152 30
        $this->methodName = substr($completeClassName, strrpos($completeClassName, '\\') + 1);
153 30
        $this->logger->info('About to perform API request', ['method' => $this->methodName]);
154
155 30
        return $this->apiUrl . $this->methodName;
156
    }
157
}
158