Completed
Push — master ( b626c0...1ad737 )
by Camilo
03:37
created

TgLog::sendRequestToTelegram()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
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
            ->then(function (TelegramResponse $response) use ($method) {
91 24
                return $method::bindToObject($response, $this->logger);
92 24
            });
93
    }
94
95
    /**
96
     * @param File $file
97
     *
98
     * @return PromiseInterface
99
     */
100
    public function downloadFile(File $file): PromiseInterface
101
    {
102
        $url = 'https://api.telegram.org/file/bot' . $this->botToken . '/' . $file->file_path;
103
        $this->logger->debug('About to perform request to begin downloading file');
104
105
        return $this->requestHandler->get($url)->then(
106
            function (TelegramResponse $rawData) {
107
                return new TelegramDocument($rawData);
108
            }
109
        );
110
    }
111
112
    /**
113
     * @param TelegramMethods $method
114
     * @param array $formData
115
     *
116
     * @return PromiseInterface
117
     */
118
    protected function sendRequestToTelegram(TelegramMethods $method, array $formData): PromiseInterface
119
    {
120
        $this->logger->debug('About to perform async HTTP call to Telegram\'s API');
121
        return $this->requestHandler->post($this->composeApiMethodUrl($method), $formData);
122
    }
123
124
    /**
125
     * Resets everything to the default values
126
     *
127
     * @return TgLog
128
     */
129 31
    final protected function resetObjectValues(): TgLog
130
    {
131 31
        $this->formConstructor->formType = 'application/x-www-form-urlencoded';
132 31
        return $this;
133
    }
134
135
    /**
136
     * Builds up the URL with which we can work with
137
     *
138
     * All methods in the Bot API are case-insensitive.
139
     * All queries must be made using UTF-8.
140
     *
141
     * @see https://core.telegram.org/bots/api#making-requests
142
     *
143
     * @param TelegramMethods $call
144
     * @return string
145
     */
146 30
    protected function composeApiMethodUrl(TelegramMethods $call): string
147
    {
148 30
        $completeClassName = get_class($call);
149 30
        $this->methodName = substr($completeClassName, strrpos($completeClassName, '\\') + 1);
150 30
        $this->logger->info('About to perform API request', ['method' => $this->methodName]);
151
152 30
        return $this->apiUrl . $this->methodName;
153
    }
154
}
155